Chinaunix

标题: paramiko为什么不能通过cd改变路径呢 [打印本页]

作者: rockyaow    时间: 2010-03-10 18:16
标题: paramiko为什么不能通过cd改变路径呢
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

请问何解?
作者: luffy.deng    时间: 2010-03-10 18:50
看看exec_command('cd /var/www/hosts')执行成功了没有。
作者: nmweizi    时间: 2010-03-10 18:51
stdin, stdout, stderr = ssh.exec_command('cd /var/www/hosts')
这后面
print stdout, stderr 看看结果
作者: nmweizi    时间: 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)
作者: rockyaow    时间: 2010-03-11 12:40
原来如此!果不其然,我w的时候根本就发现不了它,多谢nmweizi !




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2