pexpect模块实现ssh交互命令
[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()
相关文章