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()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章