发布时间:2019-07-03 12:55:04编辑:auto阅读(2177)
[root@localhost ~]# cat ex_ssh.py
#!/usr/local/python3/bin/python3
import pexpect
def exec_command(user,host,password):
new_connection = 'Are you sure you want to continue connecting'
conn = 'ssh '+user+'@'+host
child = pexpect.spawn(conn) #启动ssh命令
index = child.expect([pexpect.TIMEOUT,new_connection,'password:']) #等待程序输出,匹配字符串进行后续操作
if index == 0: #匹配到TIMEOUT
print('connect timeout')
return
if index == 1: #匹配到Are you sure you want to continue connecting
child.sendline('yes')
index = child.expect([pexpect.TIMEOUT,new_connection,'password:']) #等待程序输出,匹配字符串进行后续操作
if index == 0: #匹配到TIMEOUT
print('connect timeout')
return
child.sendline(password) #匹配到password: 发送密码
child.sendline('ls -l') #执行命令
child.sendline('uptime')
child.sendline('exit')
child.interact() #将控制权交给控制台
def main():
user = 'root' #可以使用input交互输入
host = '192.168.1.202'
password = '123456' #使用getpass.getpass('please input password: ')接受密码输入
exec_command(user,host,password)
if __name__ == '__main__':
main()
上一篇: python 模块相关知识
下一篇: 指针3
48766
47808
38585
35772
30203
26950
25984
20820
20593
18975
385°
449°
489°
498°
488°
472°
536°
599°
714°
749°