Python通過ssh連線伺服器並執行命令

2021-09-22 13:34:38 字數 1799 閱讀 6808

[本文出自天外歸雲的]

指令碼示例如下:

#

coding:utf-8

import

time,paramiko,re,stringio

defexec_shell(command):

'''command:傳入的要執行的shell命令

'''f =stringio.stringio()

header_match = '

(\[.+?@.+?\s.+?\]\$)

'ssh.send(command+'\n'

)

while

true:

out = ssh.recv(1024)

print

out,

f.write(out)

header_list =re.findall(header_match, out)

if header_list and out.strip().endswith(header_list[-1]):

break

return

fdef

check_ip(content):

'''從content中取出所有符合xx.120.xx.xx格式的ip位址(xx代表任意多數字)並返回

'''ips = re.findall('

\d+\.120\.\d+\.\d+

',content)

return

ipsif

__name__ == '

__main__':

'''host:對應要連線的伺服器ip

port:對應連線伺服器的埠

username:對應訪問伺服器的使用者名稱

'''host = '

10.120.143.70

'port = 8822username = '

bjlantianyou

''''

key_file為securecrt對應的openssh格式的私鑰檔案

可以在securecrt的'tools->convert private key to openssh format...'選擇相應的私鑰檔案轉化為openssh格式

例如:在windows下儲存到'e:\keys\'路徑下,儲存檔名為'id_rsa'

'''key_file = '

e:\\keys\\id_rsa

'key =paramiko.rsakey.from_private_key_file(key_file)

s =paramiko.sshclient()

s.load_system_host_keys()

s.set_missing_host_key_policy(paramiko.autoaddpolicy())

s.connect(host, port, username, pkey=key)

ssh =s.invoke_shell()

'''下面對應在securecrt上執行命令的過程

'''exec_shell(

'cd /home/project/api.winyyg.com')

out = exec_shell('ls'

) ips =check_ip(out.getvalue())

exec_shell(

'cat

'+ips[0]+'

/log/duobao.log

')

注意:緩衝區為空的情況下,ssh.recv(1024)會hang住。

可以進一步利用這個方法做乙個自動化過濾log的工具或平台。

Python通過ssh連線MySQL

機器a 通過機器b 登入機器c的mysql import pymysql from sshtunnel import sshtunnelforwarder server sshtunnelforwarder ssh address or host 機器b的ip 22 指定ssh登入的跳轉機的addr...

Xshell通過ssh服務連線Ubuntu

在ubuntu虛擬機器中通常只預設安裝了openssh client,也即只能通過此系統連線訪問其他系統,不具有讓其他系統訪問的許可權。通過安裝openssh server可以被其他系統訪問 此步驟中經常使用的指令ifconfig可以根據提示安裝。可能會遇到需要將虛擬網絡卡ens33改為物理網絡卡e...

python通過ssh連線伺服器,執行命令

import paramiko class linuxorder def init self,ip,port,username,password,timeout param ip 伺服器ip param port ssh 連線的埠 param username 伺服器使用者名稱 param pass...