用python paramiko ssh 服務器,并pull對應目錄代碼的腳本
pull.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
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 目錄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程序。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
#!/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 |
到這里就結束了,大家可以參考一下,方法有很多種
原文鏈接:https://www.leon0204.com/article/62.html