利用Python Paramiko和Pexpect实现远程服务器代码更新
本文介绍两种使用Python更新远程服务器代码的方法。第一种基于paramiko库,通过配置服务器列表和端口参数,实现SSH连接并执行git pull命令,适用于常规远程部署场景。第二种利用pexpect库模拟SSH交互过程,处理密码输入和主机密钥确认,适用于需要模拟终端交互的环境。文章提供了完整的代码示例及注意事项,包括权限控制和首次连接的密钥缓存处理。
使用Python的paramiko库进行SSH服务器连接,并拉取指定目录代码的脚本实现。
pull.py
import paramiko
import sys
def sshclient_execmd(hostname, port, username, password, execmd):
paramiko.util.log_to_file("paramiko.log")
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if(port==0):
s.connect(hostname=hostname, username=username, password=password)
else:
s.connect(hostname=hostname, port=port, username=username, password=password)
stdin, stdout, stderr = s.exec_command(execmd)
stdin.write("Y") # Generally speaking, the first connection, need a simple interaction.
print stdout.read()
s.close()
def main(server,project):
# def main():
server_list = {'2108':{'hostname':'112.22.22.22','username':'root','password':'123456','port':2108},
'11':{'hostname':'192.168.1.11','username':'root','password':'123456','port':0}
}
if(server == '118'):
execmd = "cd /workspace/" + project + "/ && git pull"
info = os.popen(execmd).read() # 这里是更新本地的,可以返回打印出cmd 的回显结果
print info
up_list = server_list[server]
hostname = up_list['hostname']
port = up_list['port']
username = up_list['username']
password = up_list['password']
execmd = "cd /workspace/" + project + "/ && git pull"
sshclient_execmd(hostname, port, username, password, execmd)
if __name__ == "__main__":
server = str(sys.argv[1])
project = str(sys.argv[2])
main(server,project)
上述代码实现了从远程服务器project目录拉取源码的功能。
/workspace/" + project + "/ && git pull
例如,运行命令 `python pull.py 2108 web ` 时,程序会使用 paramiko.SSHClient 模块,连接配置在 main 函数中 server_list list 字典里定义的 2108 端口的 hostname、username、password 以及 port 参数。连接成功后,将执行 execmd 中预设的命令。此处使用 argv 模块获取输入参数,以控制需要更新的项目路径。至此,一个利用Python通过SSH远程服务器并更新对应目录代码的脚本即告完成。
这里配置了两个服务器,其中编号为 11 的服务器未使用 port 参数,因此代码中加入了判断逻辑,以控制连接时是否携带 port 参数,避免因参数缺失导致连接报错。
if(port==0):
请注意,如果是首次执行连接,需要接受主机密钥缓存(author_key),同时需确保当前用户拥有相应的更新权限。
使用Python通过SSH连接远程服务器并执行命令的代码示例。
以下代码使用pexpect生成一个SSH进程,连接远程服务器并执行命令。在使用该程序前,需先通过 easy_install pexpect 安装pexpect库。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pexpect
def ssh_cmd(ip, passwd, cmd):
ret = -1
ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd))
try:
i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
if i == 0 :
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes\n')
ssh.expect('password: ')
ssh.sendline(passwd)
ssh.sendline(cmd)
r = ssh.read()
print r
ret = 0
except pexpect.EOF:
print "EOF"
ssh.close()
ret = -1
except pexpect.TIMEOUT:
print "TIMEOUT"
ssh.close()
ret = -2
return ret
介绍到此结束,大家可以参考上述方法,实现远程服务器代码的自动化更新。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









