python 使用paramiko操作linux

2021-09-11 05:52:46 字數 2571 閱讀 8770

可以利用paramiko模組寫伺服器指令碼,在本地執行,比如持續更新**,檢視日誌,批量配置集群等。

paramiko 主要包含sshclient和sftpclient兩個元件:

ssh服務會話的表示,通常用來執行命令,主要有connect、exec_command、load_system_host_keys和set_missing_host_key_policy方法。

sftp客戶端物件,實現遠端檔案操作,主要有from_transport、put、get、mkdir、remove、rename、stat、listdir等方法。

pip install paramiko

import paramiko

#伺服器資訊,主機名(ip位址)、埠號、使用者名稱及密碼

hostname = "***.***.xx.170"

port = 11022

username = "rdadmin"

password = "818"

#建立ssh物件

client = paramiko.sshclient()

#自動新增策略,儲存伺服器的主機名和金鑰資訊

client.set_missing_host_key_policy(paramiko.autoaddpolicy())

#連線伺服器

client.connect(hostname, port, username, password, compress=true)

# 執行linux命令

stdin, stdout, stderr = client.exec_command('ls /')

for line in stdout:

print('... ' + line.strip('\n'))

#orprint(stdout.readlines())

import paramiko

hostname = "192.168.0.1"

port = 22

username = "root"

password = "root"

client = paramiko.sshclient()

client.set_missing_host_key_policy(paramiko.autoaddpolicy())

client.connect(hostname, port, username, password, compress=true)

sftp_client = client.open_sftp()

remote_file = sftp_client.open("/home/verified_list.txt") #檔案路徑

try:

for line in remote_file:

print(line.strip())

finally:

remote_file.close()

import paramiko

hostname = 192.168.0.1

port = 22

username = "root"

password = "root"

transport = paramiko.transport((hostname, port))

transport.connect(username = username, password = password)

sftp = paramiko.sftpclient.from_transport(transport)

#上傳檔案

sftp.put("./video.mp4","/home/share/video.mp4")

sftp.close()

通過sshclient的invoke_shell方法,可以建立乙個互動會話的物件,和exec_command方法不同的是,這個可以實現命令互動,比如先cd到某個目錄下,再執行指令碼操作,然後退出,這種需要多個步驟的操作。

import paramiko

hostname = "192.168.0.1"

port = 22

username = "root"

password = "root"

client = paramiko.sshclient()

client.set_missing_host_key_policy(paramiko.autoaddpolicy())

client.connect(hostname, port, username, password, compress=true)

channel = client.invoke_shell() # 在ssh server端建立乙個互動式的shell

command = ""

channel.send(command + '\n')

time.sleep(10)

stdout = channel.recv(1024*100000)

out_list = stdout.decode().split("\n")

client.close()

python元類的使用 python使用元類

原文 type 動態語言和靜態語言最大的不同,就是函式和類的定義,不是編譯時定義的,而是執行時動態建立的。比方說我們要定義乙個hello的class,就寫乙個hello.py模組 當python直譯器載入hello模組時,就會依次執行該模組的所有語句,執行結果就是動態建立出乙個hello的class...

Python精通 Python函式使用

在程式設計意義上的函式其實是指完成某種操作的 塊,當然這個是個人的理解,但是這個概念在所有的程式語言中都是通用的。這個 塊用來完成某寫特定的操作。但是在數學上的函式卻是表示某種對應關係,這兩者之間還是有一定的區別的。但是在某種角度上講我們所程式設計的這種 塊其實就是表示的是引數與返回值之間的關係。從...

python 元組使用 使用元組

usr bin python filename using tuple.py zoo wolf elephant penguin print number of animals in the zoo is len zoo new zoo monkey dolphin zoo print number...