Python SSH自动化脚本



我想构建一个自动化脚本,用于在运行Linux的远程服务器上执行众多命令,并检查每个命令的"退出代码",并将其与语句

进行比较

到目前为止,作为一个绝对的初学者,我有以下内容:

import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.124.154', username='root', password='password')
stdin, stdout, stderr = client.exec_command('ls -l')
for line in stdout:
    print line.strip('n')
client.close()

您能帮我推荐吗?

child = pexpect.spawn('ssh admin@' +ip)
child.expect ('Login: ')
child.sendline (username)
child.expect ('Password: ')
child.sendline (password)
child.expect('#') # or expect `$`.
child.sendline('<your command>')
child.expect('#')
print child.before

ref:http://pexpect.sourceforge.net/pexpect.html

使用pexpect更容易。

您可以使用为此设计的附庸包。

您需要的只是安装盒子并做

from vassal.terminal import Terminal
shell = Terminal(["ssh username@host", "cd scripts", "python foo1.py", "python foo2.py"])
shell.run()

它将在Python中启动一个交互式窗口,您可以从中解析出口代码。另外,它将为您节省身份验证,而无需一次又一次地键入它们。

最新更新