免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 11247 | 回复: 4
打印 上一主题 下一主题

paramiko为什么不能通过cd改变路径呢 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-03-10 18:16 |只看该作者 |倒序浏览
ssh=paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try :
        ssh.connect(hostname,port,username,password)
    except :
        print 'shit error'
        sys.exit(5)



    stdin, stdout, stderr = ssh.exec_command('pwd')
    print stdout.read()               #结果为 /root
    stdin, stdout, stderr = ssh.exec_command('cd /var/www/hosts')
    stdin, stdout, stderr = ssh.exec_command('pwd')
    print stdout.read()               #结果应该变为 /var/www/hosts,但还是/root

请问何解?

论坛徽章:
0
2 [报告]
发表于 2010-03-10 18:50 |只看该作者
看看exec_command('cd /var/www/hosts')执行成功了没有。

论坛徽章:
0
3 [报告]
发表于 2010-03-10 18:51 |只看该作者
stdin, stdout, stderr = ssh.exec_command('cd /var/www/hosts')
这后面
print stdout, stderr 看看结果

论坛徽章:
0
4 [报告]
发表于 2010-03-10 19:10 |只看该作者
本帖最后由 nmweizi 于 2010-03-10 19:17 编辑

Python Remote SSH with Paramiko

I am using Paramiko to do some remote ssh work and could not figure out how to change directories and execute a script with the SSHClient.execute_command() function. I finally figured out that .execute_command() is basically a single session, so doing a .execute_command('cd scripts') and then executing the script with another .execute_command() reverts back to your default directory. The alternatives are to send all the commands at once separated by a ; .execute_command('cd scripts; ./myscript.sh'), or to use the .interactive() shell support. Since I only needed to fire off this script I used the first solution.


意思就是execute_command() 他是a single session,每次执行完后都要回到缺省目录。所以可以 .execute_command('cd  /var; pwd')

或者使用aa = ssh.invoke_shell()
aa.send('cd /var\n')
aa.recv(100)

论坛徽章:
0
5 [报告]
发表于 2010-03-11 12:40 |只看该作者
原来如此!果不其然,我w的时候根本就发现不了它,多谢nmweizi !
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP