用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 的 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 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
新聞熱點
疑難解答