摘要:模塊為的縮寫(xiě),由的網(wǎng)絡(luò)小組所制定為建立在應(yīng)用層基礎(chǔ)上的安全協(xié)議。是目前較可靠,專為遠(yuǎn)程登錄會(huì)話和其他網(wǎng)絡(luò)服務(wù)提供安全性的協(xié)議。利用該模塊,可以方便的進(jìn)行連接和協(xié)議進(jìn)行文件傳輸。
paramiko模塊
SSH 為 Secure Shell 的縮寫(xiě),由 IETF 的網(wǎng)絡(luò)小組(Network Working Group)所制定;SSH 為建立在應(yīng)用層基礎(chǔ)上的安全協(xié)議。SSH 是目前較可靠,專為遠(yuǎn)程登錄會(huì)話和其他網(wǎng)絡(luò)服務(wù)提供安全性的協(xié)議。利用 SSH 協(xié)議可以有效防止遠(yuǎn)程管理過(guò)程中的信息泄露問(wèn)題.
paramiko是用python語(yǔ)言寫(xiě)的一個(gè)模塊,遵循SSH2協(xié)議,支持以加密和認(rèn)證的方式,進(jìn)行遠(yuǎn)程服務(wù)器的連接。paramiko支持Linux, Solaris, BSD, MacOS X, Windows等平臺(tái)通過(guò)SSH從一個(gè)平臺(tái)連接到另外一個(gè)平臺(tái)。利用該模塊,可以方便的進(jìn)行ssh連接和sftp協(xié)議進(jìn)行sftp文件傳輸。
遠(yuǎn)程密碼連接#基于ssh,用于連接遠(yuǎn)程服務(wù)器做操作:遠(yuǎn)程執(zhí)行命令,上傳或下載文件
import paramiko
#創(chuàng)建一個(gè)ssh對(duì)象
client = paramiko.SSHClient()
#2.解決問(wèn)題:首次連接,會(huì)出現(xiàn)
# Are you sure you want to continue connecting (yes/no)? yes
# 自動(dòng)選擇yes
# 允許連接不在know_hosts文件中的主機(jī)
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#3.連接服務(wù)器
client.connect(hostname="172.25.254.19",port=22,username="root",password="westos")
#4.執(zhí)行操作
stdin,stdout,stderr = client.exec_command("hostname")#標(biāo)準(zhǔn)輸入,標(biāo)準(zhǔn)輸出,標(biāo)準(zhǔn)錯(cuò)誤輸出。
#Execute a command on the SSH server. A new `.Channel` is opened and
# the requested command is executed. The command"s input and output
# streams are returned as Python ``file``-like objects representing
# stdin, stdout, and stderr.
#5.獲取命令的執(zhí)行結(jié)果
res = stdout.read().decode("utf-8")#使結(jié)果具有可讀性
print(res)
#6.斷開(kāi)連接
client.close()
批量連接
批量連接host.txt文件中的主機(jī),返回執(zhí)行結(jié)果
格式:172.25.254.1:22:root:westos
import paramiko
with open("host.txt") as f: #保證host.txt文件在當(dāng)前目錄下
hostinfos = f.readlines() #列表形式,["172.25.254.1:22:root:westos
", "172.25.254.2:22:root:westos
", "172.25.254.3:22:root:westos
", "172.25.254.19:22:root:westos
"]
for hostinfo in hostinfos:
hostinfo = hostinfo.strip() #去掉空格,字符串格式,172.25.254.2:22:root:westos
print("正在連接%s主機(jī)" %(hostinfo.split(":")[0]))
hostname,port,username,passwd = hostinfo.split(":")
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=hostname,port=port,username=username,password=passwd)
stdin,stdout,stderr = client.exec_command("hostname")
res = stdout.read().decode("utf-8")
print("結(jié)果為:",res)
except Exception as e :
print("Connection is failed,the reason is :",e)
finally:
client.close()
print("連接結(jié)束")
基于公鑰連接
免密登錄遠(yuǎn)程主機(jī)
首先在需要連接的主機(jī)上生成一對(duì)公鑰和私鑰,本機(jī)獲取到需要連接的主機(jī)的私鑰時(shí),就可以通過(guò)公私鑰配對(duì),登陸遠(yuǎn)程主機(jī)。
這里需要id_rsa存放你所連接的主機(jī)的私鑰
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
def conn(cmd,hostname,port=22,username="root"):
client = paramiko.SSHClient()
private_key = paramiko.RSAKey.from_private_key_file("id_rsa")#id_rsa存放私鑰
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=hostname,
port=port,username=username,pkey=private_key)
except NoValidConnectionsError as e:
print("...連接失敗...")
except AuthenticationException as e:
print("...密碼錯(cuò)誤...")
else:
stdin, stdout, stderr = client.exec_command(cmd)
result = stdout.read().decode("utf-8")
print(result)
finally:
client.close()
if __name__=="__main__":
for count in range(13,20):
hostname = "172.25.254.%s" %(count)
print("正在連接主機(jī):",hostname)
conn("hostname",hostname)
print("...連接結(jié)束...")
基于用戶名密碼上傳下載文件
sftp是Secure File Transfer Protocol的縮寫(xiě),安全文件傳送協(xié)議。可以為傳輸文件提供一種安全的網(wǎng)絡(luò)的加密方法。
import paramiko
tran = paramiko.Transport("172.25.254.19",22)
tran.connect(username="root",password="westos")
sftp = paramiko.SFTPClient.from_transport(tran)
#class SFTPClient(BaseSFTP, ClosingContextManager)
#SFTP client object.
# Used to open an SFTP session across an open SSH `.Transport` and perform
# remote file operations.
# Instances of this class may be used as context managers.
sftp.put("/home/kiosk/PycharmProjects/day18/07_pratice.py","/mnt/practice.py")
sftp.get("/mnt/passwd","hallo")
tran.close()
paramiko再封裝
使paramiko模塊執(zhí)行自己想要的操作
import paramiko
import os
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException, SSHException
class SshRrmote(object):
def __init__(self,cmd,hostname,port,username,passwd):
self.hostname = hostname
self.passwd = passwd
self.cmd = cmd
self.username = username
self.port = port
def run(self):
"""默認(rèn)調(diào)用的內(nèi)容"""
# cmd hostname
# put local_file remote_file
# get remote_file local_file
cmd_str = self.cmd.split()[0] # cmd
# 類的反射, 判斷類里面是否可以支持該操作?
if hasattr(self, "do_" + cmd_str): # do_cmd
getattr(self, "do_" + cmd_str)()
else:
print("目前不支持該功能")
def do_cmd(self):
client = paramiko.SSHClient()
try:
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=self.hostname,port=int(self.port),username=self.username,password=self.passwd)
except NoValidConnectionsError as e:
print("...連接失敗...")
except AuthenticationException as e:
print("...密碼錯(cuò)誤...")
else:
cmd = " ".join(self.cmd.split()[1:])
stdin, stdout, stderr = client.exec_command(cmd)
result = stdout.read().decode("utf-8")
print("執(zhí)行結(jié)果",result)
finally:
print("斷開(kāi)%s的連接" %(self.hostname))
client.close()
def do_get(self):
#有待改進(jìn),因?yàn)檫B接多個(gè)主機(jī)時(shí),會(huì)覆蓋文件
print("開(kāi)始下載")
try:
trans = paramiko.Transport(self.hostname,int(self.port))
trans.connect(username=self.username,password=self.passwd)
print("hello")
except SSHException as e:
print("連接失敗")
else:
sftp = paramiko.SFTPClient.from_transport(trans)
cmd = self.cmd.split()[1:]
if len(cmd)==2:
sftp.get(cmd[0],cmd[1])
print("下載文件%s成功,并保存為%s" %(cmd[0],cmd[1]))
else:
print("參數(shù)有誤")
trans.close()
def do_put(self):
# put /tmp/passwd /tmp/passwd # 將本機(jī)的/tmp/passwd文件上傳到遠(yuǎn)程主機(jī)的/tmp/passwd;
print("開(kāi)始上傳") #注意你使用的用戶是否為kiosk
try:
trans = paramiko.Transport(self.hostname, int(self.port))
trans.connect(username=self.username, password=self.passwd)
except SSHException as e:
print("連接失敗")
else:
sftp = paramiko.SFTPClient.from_transport(trans)
cmd = self.cmd.split()[1:]
if len(cmd) == 2:
sftp.put(cmd[0],cmd[1])
print("上傳文件%s成功,并保存為%s" %(cmd[0], cmd[1]))
else:
print("參數(shù)有誤")
trans.close()
#1.選擇要操作的主機(jī)組:mysql,web,ftp
# 主機(jī)信息怎么存?將不同的主機(jī)信息存放在不同的文件中
#2.根據(jù)選擇的主機(jī)組,顯示包含的主機(jī)IP/主機(jī)名
#3.讓用戶確認(rèn)信息,選擇需要批量執(zhí)行的命令
# -cmd shell命令
# -put 本地文件 遠(yuǎn)程文件
# -get 遠(yuǎn)程文件 本地文件
def main():
groups = [file.rstrip(".conf") for file in os.listdir("conf")]
print("主機(jī)組顯示".center(50,"*"))
[print(" ",item) for item in groups]
choiceGroup = input("請(qǐng)選擇批量操作的主機(jī)組(eg:web):")
with open("conf/"+choiceGroup+".conf") as f:
info = f.readlines()
print("批量執(zhí)行腳本".center(50, "*"))
while True:
cmd = input(">>").strip()
if cmd:
if cmd =="exit":
print("連接執(zhí)行結(jié)束")
break
for item in info:
item=item.strip()
print(item.split(":")[0].center(50,"-"))
hostname,port,username,passwd = item.split(":")
ssh = SshRrmote(cmd,hostname,port,username,passwd)
ssh.run()
main()
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.hztianpu.com/yun/42458.html
摘要:是一個(gè)用于做遠(yuǎn)程控制的模塊,使用該模塊可以對(duì)遠(yuǎn)程服務(wù)器進(jìn)行命令或文件操作,值得一說(shuō)的是,和內(nèi)部的遠(yuǎn)程管理就是使用的來(lái)現(xiàn)實(shí)。 paramiko paramiko是一個(gè)用于做遠(yuǎn)程控制的模塊,使用該模塊可以對(duì)遠(yuǎn)程服務(wù)器進(jìn)行命令或文件操作,值得一說(shuō)的是,fabric和ansible內(nèi)部的遠(yuǎn)程管理就是使用的paramiko來(lái)現(xiàn)實(shí)。 1、下載安裝 pycrypto,由于 paramiko 模塊內(nèi)部...
摘要:協(xié)程實(shí)現(xiàn)連接在網(wǎng)絡(luò)通信中,每個(gè)連接都必須創(chuàng)建新線程或進(jìn)程來(lái)處理,否則,單線程在處理連接的過(guò)程中,無(wú)法接受其他客戶端的連接。所以我們嘗試使用協(xié)程來(lái)實(shí)現(xiàn)服務(wù)器對(duì)多個(gè)客戶端的響應(yīng)。 協(xié)程實(shí)現(xiàn)TCP連接 在網(wǎng)絡(luò)通信中,每個(gè)連接都必須創(chuàng)建新線程(或進(jìn)程) 來(lái)處理,否則,單線程在處理連接的過(guò)程中, 無(wú)法接受其他客戶端的連接。所以我們嘗試使用協(xié)程來(lái)實(shí)現(xiàn)服務(wù)器對(duì)多個(gè)客戶端的響應(yīng)。與單一TCP通信的構(gòu)架...
摘要:是建立可靠連接,并且通信雙方都可以以流的形式發(fā)送數(shù)據(jù)。相對(duì),則是面向無(wú)連接的協(xié)議。測(cè)試結(jié)果用兩個(gè)命令行分別啟動(dòng)服務(wù)器和客戶端測(cè)試開(kāi)啟服務(wù)端完成一次通信 UDP TCP是建立可靠連接, 并且通信雙方都可以以流的形式發(fā)送數(shù)據(jù)。 相對(duì)TCP, UDP則是面向無(wú)連接的協(xié)議。使用UDP協(xié)議時(shí), 不需要建立連接, 只需要知道對(duì)方的IP地址和端口號(hào), 就可以直接發(fā)數(shù)據(jù)包。 但是, 能不能到達(dá)就不知道...
摘要:是基于實(shí)現(xiàn)的遠(yuǎn)程安全連接,支持認(rèn)證及密鑰方法。利用函數(shù)發(fā)送到,通過(guò)函數(shù)獲取回顯。如下全局屬性設(shè)定對(duì)象的作用是定義的全局設(shè)定,支持多個(gè)屬性及自定義屬性。相比確實(shí)簡(jiǎn)化了不少。出現(xiàn)異常時(shí),發(fā)出警告,繼續(xù)執(zhí)行,不要終止。 paramiko paramiko是基于Python實(shí)現(xiàn)的SSH2遠(yuǎn)程安全連接,支持認(rèn)證及密鑰方法??梢詫?shí)現(xiàn)遠(yuǎn)程命令執(zhí)行,文件傳輸,中間SSH代理等功能,相對(duì)于Pexpect...
摘要:數(shù)據(jù)傳輸方式輸入類控件表單元素也稱表單控件,按照填寫(xiě)方式分為輸入類和下拉菜單類。按鈕的名字按鈕上顯示的文本重置菜單列表控件下拉菜單可以節(jié)省頁(yè)面空間。是單標(biāo)簽,用來(lái)定義下拉菜單中的選項(xiàng)。表示初始被選中的選項(xiàng)。 當(dāng)用戶熟悉了靜態(tài)網(wǎng)頁(yè)制作后就能感受到它的功能單一,會(huì)想建立具有交互性的動(dòng)態(tài)網(wǎng)站。動(dòng)態(tài)網(wǎng)站經(jīng)常用到的一個(gè)元素就是表單。表單是HTML的一個(gè)重要組成部分,是網(wǎng)站管理員與用戶之間溝通的橋...
閱讀 2238·2023-04-25 17:57
閱讀 1346·2021-11-24 09:39
閱讀 2556·2019-08-29 16:39
閱讀 3383·2019-08-29 13:44
閱讀 3234·2019-08-29 13:14
閱讀 2403·2019-08-26 11:36
閱讀 3909·2019-08-26 11:00
閱讀 988·2019-08-26 10:14