如何利用python更新ssh远程代码

  介绍

这篇文章将为大家详细讲解有关如何利用python更新ssh远程代码,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

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

拉。py

import  paramiko   import 系统      def  sshclient_execmd(主机名,端口,用户名,密码,execmd):   paramiko.util.log_to_file才能(“paramiko.log")      时间=s 才能;paramiko.SSHClient ()   s.set_missing_host_key_policy才能(paramiko.AutoAddPolicy ())   如果才能(端口==0):   ,,,s.connect(=主机名、主机名,用户名=用户名,密码(密码)   其他的才能:   ,,,s.connect(=主机名、主机名,端口=端口,,用户名=用户名,密码(密码)   ,,,stdin、stdout, stderr =, s.exec_command (execmd)   stdin.write才能(“Y"), #, Generally 来说,,,first 连接,need  a  simple 交互。      print 才能;stdout.read ()      s.close才能()         def 主要(服务器、项目):   #,def  main ():   server_list 才能=,{& # 39;2108 & # 39;:{& # 39;主机名# 39;:& # 39;112.22.22.22& # 39;,& # 39;用户名# 39;:& # 39;根# 39;,& # 39;密码# 39;:& # 39;123456 & # 39;,& # 39;港口# 39;:2108},   ,,,,,,,,& # 39;11 & # 39;:{& # 39;主机名# 39;:& # 39;192.168.1.11& # 39;,& # 39;用户名# 39;:& # 39;根# 39;,& # 39;密码# 39;:& # 39;123456 & # 39;,& # 39;港口# 39;:0}   ,,,,,,,,,}      如果才能(server ==, & # 39; 118 & # 39;):   ,,,execmd =,“cd /workspace/? +, project  +,“/,,,, git  pull"   ,,,info =, os.popen (execmd) .read(),, #,这里是更新本地的,可以返回打印出cmd 的回显结果   ,,,print 信息      时间=up_list 才能;server_list(服务器)   hostname 才能=,up_list[& # 39;主机名# 39;】   port 才能=,up_list[& # 39;港口# 39;】   username 才能=,up_list[& # 39;用户名# 39;】   时间=password 才能;up_list[& # 39;密码# 39;】      execmd =,才能“cd /workspace/? +, project  +,,,/,,,, git  pull"   sshclient_execmd才能(主机名,端口,用户名,密码,execmd)         if  __name__ ==,“__main__":   server 才能=,str (sys.argv [1])   project 才能=,str (sys.argv [2])   主要的才能(服务器、项目)

上面的是更新远程服务器上项目目录拉的源码。

<代码>/workspace/?项目+,/,,git拉

比如运行”<代码> python拉。py 2108网络> paramiko。SSHClient> 主要函数中的<代码> 中server_list列表的2108年的<代码>主机名,<代码>用户名,<代码>密码,<代码> 港参数,连接服务器后,执行<代码> execmd> argv 获取输入的参数,来控制要更新的项目路径。这样一个利用python ssh远程服务器,并更新对应目录代码的脚本就完成了。

这里我配置了两个服务器,这11个服务器,没有使用到<代码>端口> 港参数,不然会报错。

<代码>如果(端口==0):

这里注意,如果是第一次执行需要接受author_key缓存,还需要注意是否有更新权限

<强> python使用ssh连接远程服务器,并执行命令代码

下面的代码使用pexpect生成一个ssh进程,然后连接远程服务器,并执行命令。
在使用下面程序之前,需要先通过easy_install pexpect安装pexpect程序。

# !/usr/bin/env  python   #,- *安康;编码:utf-8  - * -      import  pexpect      def  ssh_cmd (ip, passwd, cmd):   ret 才能=1   ssh 才能=,pexpect.spawn (& # 39; ssh  root@ % s “% s" & # 39;, %, (ip, cmd))   尝试才能:   ,,,小姐:=,ssh.expect((& # 39;密码:& # 39;,,& # 39;continue  connecting (是/否)? & # 39;],,超时=5)   ,,,if 小姐:==,0,:   ,,,,,ssh.sendline(密码)   ,,,elif 小姐:==,1:   ,,,,,ssh.sendline(& # 39;是的\ n # 39;)   ,,,,,ssh.expect(& # 39;密码:,& # 39;)   ,,,,,ssh.sendline(密码)   ,,,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

如何利用python更新ssh远程代码