前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >pexpect模块实现ssh交互命令

pexpect模块实现ssh交互命令

作者头像
py3study
发布2020-01-14 12:37:52
8400
发布2020-01-14 12:37:52
举报
文章被收录于专栏:python3python3

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档