首页 > 开发 > Python > 正文

利用python 更新ssh 远程代码 操作远程服务器的实现代码

2020-07-28 14:49:26
字体:
来源:转载
供稿:网友

用python paramiko ssh 服务器,并pull对应目录代码的脚本

pull.py

import paramikoimport sysdef 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 目录pull 的源码。

/workspace/" + project + "/ && git pull

比如运行 `python pull.py 2108 web ` 就会 用 paramiko.SSHClient, 来连接 配置于 main 函数中的 server_list list 中的 2108 的 hostnameusernamepasswordport 参数,连接服务器后,执行 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 pexpectdef 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 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表