连接到putty,通过python使用相同的会话登录到第二个linux服务器

时间:2012-07-12 15:24:30

标签: python putty

有没有办法:
1。打开putty / plink会话并通过python登录linux服务器
2。在当前会话中通过python登录到另一个Linux服务器
3。让putty会话打开并可供用户手动运行其他命令吗?

注意:
- 脚本需要在通过putty访问linux服务器的Windows机器上运行。
- 使用subprocess.Popen()很容易。
- 我坚持为下次服务器登录发送密码。 RSA ssh密钥在我们的服务器上受到限制。

有什么想法吗?可能是python脚本的其他替代方法吗?

1 个答案:

答案 0 :(得分:1)

是的,你可以这样做。使用pexpect

但我必须注意,如果不安装cygwin,就不能在windows上使用pexpect。如果要在没有cygwin的情况下直接在Windows上运行程序,则需要使用winexpecthttps://bitbucket.org/geertj/winpexpect/wiki/Home)。

Pexpect / Winexpect使用example

#!/usr/bin/env python
import pexpect

ssh_newkey = 'Are you sure you want to continue connecting'
# my ssh command line
p=pexpect.spawn('ssh mysurface@192.168.1.105 uname -a')

i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
    print "I say yes"
    p.sendline('yes')
    i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
    print "I give password",
    p.sendline("mypassword")
    p.expect(pexpect.EOF)
elif i==2:
    print "I either got key or connection timeout"
    pass
print p.before # print out the result

在您的情况下,您必须使用plink代替sshwinexpect代替pexpect

相关问题