python利用paramiko執行伺服器命令

2022-07-24 02:30:11 字數 2229 閱讀 4119

話不多說直接上**

封裝連線

@staticmethod

defconnect(ip, server_user, server_port, server_path):

"""連線伺服器

:param :

:return:

"""ssh =paramiko.sshclient()

private_key = paramiko.rsakey.from_private_key_file('

{}.ssh/id_rsa

'.format(server_path))

ssh.set_missing_host_key_policy(paramiko.autoaddpolicy())

try:

ssh.connect(ip, port=server_port, username=server_user, pkey=private_key, timeout=5, allow_agent=true)

return

ssh

except

exception as e:

'connect_error info is {}

'.format(e.__repr__

()))

return

在伺服器執行命令

def

fabric_run_cmd(self, ip, server_user, server_port, server_path, cmd):

"""批量在伺服器執行命令

:return:

"""conn =self.connect(ip, server_user, server_port, server_path)

try:

if type(conn) ==dict:

return

conn

else

: stdin, stdout, stderr =conn.exec_command(cmd)

'fabric_run_cmd_stdout info is {}

'.format(stdout.readlines()))

'fabric_run_cmd_stderr info is {}

'.format(stderr.readlines()))

channel =stdout.channel

status =channel.recv_exit_status()

conn.close()

'fabric_run_cmd_status info is {}

'.format(status))

if status ==0:

return

else

:

return

except

exception as e:

'fabric_run_cmd_error info is {}

'.format(e.__repr__

()))

return

將檔案傳送到伺服器

def

fabric_put_file(self, ip, src_file, dst_file, server_user, server_port, server_path):

"""傳送檔案到伺服器

:return:

"""conn =self.connect(ip, server_user, server_port, server_path)

if type(conn) ==dict:

return

conn

else

:

try:

ftp =conn.open_sftp()

ftp.put(dst_file, src_file)

#傳送檔案之前先判斷有沒有目標資料夾 如果沒有現在伺服器上建立資料夾

ftp.close() #

在此判斷檔案是否傳送成功

return

except

exception as e:

'fabric_put_file_error info is {}

'.format(e.__repr__

()))

return

Python 利用pymmseq cpp實現分詞

在python這pymmseg cpp 還是十分方便的!環境 ubuntu10.04 python2.65 步驟 2 tar zxf pymmseg cpp tar.gz 解壓後得到pymmseg 目錄 cd pymmseg mmseg cpp python build.py 生成 mmseg.so...

python利用ElementTree讀寫xml

1.寫xml from xml.etree.elementtree import element,subelement,elementtree 生成根節點 root element root 生成第乙個子節點 head head subelement root,head head 節點的子節點 ti...

利用Python傳送email

引入smtplib和email.mime.text.mimetextimport smtplib 將你寫的字串轉化為郵件的文字形式 from email.mime.text import mimetext smtp伺服器位址 smtp server smtp.163.com 傳送者是誰 sender...