python 模拟ssh 登录远程服务器
前言
如果你跟我一样,不愿意使用 xshell 第三方工具来远程登录自己的服务器,只想使用原生的系统 terminal来做登录,那么一下的案例会让你如愿。
安装 pexpect 模块
pip install pexpect
案例
#!/usr/local/bin/python3 import pexpect ip = “xx.xx.xx.xx” user = "root" ssh_cmd = "/usr/bin/ssh -i ~/Documents/servers/certificate/yinguohai {0}@{1}".format(user, ip) # 初始化ssh命令 child = pexpect.spawn(ssh_cmd) # 在流中寻找, 分号 ":" 所在的位置,为什么要用分号来定位,下面有解释 child.expect(":") # sendline 发送的 密码 “yinguohai" 追加到 上面 分号所寻找到的位置,并回车 child.sendline("yinguohai") # 将进程交给持有键盘的人 child.interact()
效果:
说明:
child.expect(“:”) 中我之所以需要在流中定位 分号 “:” 的位置,而不是其它的符号,是因为提示我输入密码的提示符如下图所示
所以,我用expect 在用“:”来定位,很多人登录不成功,报如下的错误基本上都是这个地方搞错了
错误信息一般类似这种:
before (last 100 chars): b"Enter passphrase for key '/Users/yinguohai/Documents/servers/certificate/yinguohai': " after: <class 'pexpect.exceptions.TIMEOUT'> match: None match_index: None exitstatus: None flag_eof: False pid: 31935 child_fd: 5 closed: False timeout: 30 delimiter: <class 'pexpect.exceptions.EOF'> logfile: None logfile_read: None logfile_send: None maxread: 2000 ignorecase: False