欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中paramiko模塊的基礎(chǔ)操作與排錯(cuò)問題

 更新時(shí)間:2022年09月07日 16:19:57   作者:程序員-小李  
python的ssh庫操作需要引入一個(gè)遠(yuǎn)程控制的模塊——paramiko,可用于對(duì)遠(yuǎn)程服務(wù)器進(jìn)行命令或文件操作,這篇文章主要介紹了Python學(xué)習(xí)之paramiko模塊的基礎(chǔ)操作與排錯(cuò),需要的朋友可以參考下

關(guān)于

python的ssh庫操作需要引入一個(gè)遠(yuǎn)程控制的模塊——paramiko,可用于對(duì)遠(yuǎn)程服務(wù)器進(jìn)行命令或文件操作。

應(yīng)用

登陸服務(wù)器,問題排查??捎糜诰帉懩_本,在服務(wù)器上做一些繁瑣的重復(fù)操作。

安裝

打開cmd,輸入命令python -m pip install paramiko

示例

1.秘鑰登陸

配置免密登錄,linux上信任了windows的公鑰,然后腳本在windows上跑,使用windows的私鑰就可以直接不要密碼登錄linux

注意:提供秘鑰的paramiko.RSAKey.from_private_key_file('文件'),這里面的"文件"是你本機(jī)上的秘鑰,不是指你被控機(jī)上的公鑰哦!

import paramiko

key = paramiko.RSAKey.from_private_key_file("C:\\Users\\liyansheng\\.ssh\\id_rsa")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print("connecting")
ssh.connect(hostname="192.168.220.128", username="root", pkey=key)
print("connected")
commands = "uname -a"
stdin, stdout, stderr = ssh.exec_command(commands)
stdin.close()
res, err = stdout.read(), stderr.read()
result = res if res else err
print(result)
ssh.close()

if __name__ == '__main__':
    print()

2.單個(gè)命令執(zhí)行

1.創(chuàng)建一個(gè).py文件,引入 paramiko模塊

import paramiko

2.建立SSHClient對(duì)象

ssh = paramiko.SSHClient()

3.設(shè)置可信任,將主機(jī)加到host_allow列表

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

4.創(chuàng)建連接

ssh.connect("150.158.16.123", 22, "wuyanping", "2022")

5.創(chuàng)建命令,發(fā)送并獲取響應(yīng)結(jié)果

 stdin, stdout, stderr = ssh.exec_command("ls /home")
    print(stdout.read().decode("utf-8"))

6.關(guān)閉連接

ssh.close()

3.執(zhí)行多個(gè)命令

# 執(zhí)行多條命令,注意傳入的參數(shù)有個(gè)list
def execMultiCmd(host, user, psw, cmds: list, port=22) -> (str, str):
    with paramiko.SSHClient() as ssh_client:
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname=host, port=port, username=user, password=psw)
        cmd = ";".join(cmds)
        _, stdout, stderr = ssh_client.exec_command(cmd, get_pty=True)
        result = stdout.read().decode('utf-8')
        err = stderr.read().decode('utf-8')
    return result, err


if __name__ == '__main__':
    cmdList = ["cd /home", "ls"]
    print(execMultiCmd("192.168.220.128", "root", "root", cmdList))

4.SFTPClient下載文件

方法封裝:

def down_file(host, user, psw, local_file, remote_file, port=22):
    with paramiko.Transport((host, port)) as transport:
        # 連接服務(wù)
        transport.connect(username=user, password=psw)
        # 獲取SFTP示例
        sftp = paramiko.SFTPClient.from_transport(transport)
        # 下載
        sftp.get(remote_file, local_file)
        transport.close()

問題:(錯(cuò)誤)

if __name__ == '__main__':
    down_file(my_linux.host, my_linux.user, my_linux.psw, "D:\\ssh_download", "/home/test.txt")
Traceback (most recent call last):
  File "D:\MyCode2\py-1\ssh\download.py", line 17, in <module>
    down_file("192.168.220.128", "root", "root", "D:\\ssh_download", "/home/test.txt")
  File "D:\MyCode2\py-1\ssh\download.py", line 11, in down_file
    sftp.get(remote_file, local_file)
  File "D:\MyCode2\py-1\venv\lib\site-packages\paramiko\sftp_client.py", line 810, in get
    with open(localpath, "wb") as fl:
PermissionError: [Errno 13] Permission denied: 'D:\\ssh_download'

正確使用

要指定下載的文件名,不能只是一個(gè)目錄

if __name__ == '__main__':
    down_file(my_linux.host, my_linux.user, my_linux.psw, "D:\\ssh_download\\test.txt", "/home/test.txt")

5.上傳文件

def upload_file(host, user, psw, local_file, remote_file, port=22):
    with paramiko.Transport((host, port)) as transport:
        # 連接服務(wù)
        transport.connect(username=user, password=psw)
        # 獲取SFTP示例
        sftp = paramiko.SFTPClient.from_transport(transport)
        sftp.put(local_file, remote_file)
        transport.close()

測(cè)試同下載,特別要注意路徑問題。如

if __name__ == '__main__':
    upload_file(my_linux.host, my_linux.user, my_linux.psw, "D:\\ssh_download\\test123.txt", "/home/test/test123.txt")

6.ssh工具封裝

import os

import paramiko


class SSHTool():
    def __init__(self, ip, port, user, psw):
        """
        初始化
        :param ip:
        :param port:
        :param user:
        :param psw:
        """
        self.ip = ip
        self.port = port
        self.user = user
        self.psw = psw

    def connect_ssh(self):
        """
        創(chuàng)建連接
        :return:
        """
        try:
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh.connect(
                hostname=self.ip,
                port=self.port,
                username=self.user,
                password=self.psw
            )
        except Exception as e:
            print(e)
        return self.ssh

    def close_ssh(self):
        """
        關(guān)閉連接
        :return:
        """
        try:
            self.ssh.close()
        except Exception as e:
            print(e)

    def exec_shell(self, shell):
        ssh = self.connect_ssh()
        try:
            stdin, stdout, stderr = ssh.exec_command(shell)
            return stdin, stdout, stderr
        except Exception as e:
            print(e)

    def sftp_put_file(self, file, local_dir, remote_dir):
        try:
            t = paramiko.Transport((self.ip, self.port))
            t.connect(username=self.user, password=self.psw)
            sftp = paramiko.SFTPClient.from_transport(t)
            sftp.put(os.path.join(local_dir, file), remote_dir)
            t.close()
        except Exception:
            print("connect error!")

    def sftp_get_file(self, file, local_dir, remote_dir):
        try:
            t = paramiko.Transport((self.ip, self.port))
            t.connect(username=self.user, password=self.psw)
            sftp = paramiko.SFTPClient.from_transport(t)
            sftp.get(remote_dir, os.path.join(local_dir, file))
            t.close()
        except Exception:
            print("connect error!")

補(bǔ)充

獲取當(dāng)前文件路徑:os.getcwd()

import os

if __name__ == '__main__':
    print(os.getcwd())  # D:\MyCode2\py-1\ssh

python函數(shù)返回多個(gè)參數(shù)

def get_strs() -> (str, str):
    return "hello", "word"
if __name__ == '__main__':
    # 返回值為元祖的形式
    print(get_strs())  # ('hello', 'word')
    # 獲取元祖的個(gè)數(shù)
    print(len(get_strs()))  # 2
    # 通過下標(biāo)獲取元祖的某一個(gè)值
    print(get_strs().__getitem__(1))  # word
    # 通過元祖的某個(gè)元素定位對(duì)應(yīng)的下標(biāo)
    print(get_strs().index("hello"))  # 0

with … as …使用

為了更好地避免此類問題,不同的編程語言都引入了不同的機(jī)制。在 Python 中,對(duì)應(yīng)的解決方式是使用 with as 語句操作上下文管理器(context manager),它能夠幫助我們自動(dòng)分配并且釋放資源。簡(jiǎn)單的理解,同時(shí)包含 enter() 和 exit() 方法的對(duì)象就是上下文管理器。

格式:

with 表達(dá)式 [as target]:
    代碼塊

學(xué)習(xí)參考

到此這篇關(guān)于Python學(xué)習(xí)之paramiko模塊的基礎(chǔ)操作與排錯(cuò)的文章就介紹到這了,更多相關(guān)Python paramiko模塊內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python redis 批量設(shè)置過期key過程解析

    python redis 批量設(shè)置過期key過程解析

    這篇文章主要介紹了python redis 批量設(shè)置過期key過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • 詳解在Python中處理異常的教程

    詳解在Python中處理異常的教程

    這篇文章主要介紹了詳解在Python中處理異常的教程,是Python入門中的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-05-05
  • tensorflow之變量初始化(tf.Variable)使用詳解

    tensorflow之變量初始化(tf.Variable)使用詳解

    今天小編就為大家分享一篇tensorflow之變量初始化(tf.Variable)使用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • python3實(shí)現(xiàn)磁盤空間監(jiān)控

    python3實(shí)現(xiàn)磁盤空間監(jiān)控

    這篇文章主要為大家詳細(xì)介紹了python3實(shí)現(xiàn)磁盤空間監(jiān)控,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-06-06
  • Python_LDA實(shí)現(xiàn)方法詳解

    Python_LDA實(shí)現(xiàn)方法詳解

    這篇文章主要介紹了Python_LDA實(shí)現(xiàn)方法詳解,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-10-10
  • Python實(shí)現(xiàn)http接口自動(dòng)化測(cè)試的示例代碼

    Python實(shí)現(xiàn)http接口自動(dòng)化測(cè)試的示例代碼

    這篇文章主要介紹了Python實(shí)現(xiàn)http接口自動(dòng)化測(cè)試的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • opencv 圖像輪廓的實(shí)現(xiàn)示例

    opencv 圖像輪廓的實(shí)現(xiàn)示例

    這篇文章主要介紹了opencv 圖像輪廓的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • python檢查指定文件是否存在的方法

    python檢查指定文件是否存在的方法

    這篇文章主要介紹了python檢查指定文件是否存在的方法,涉及Python基于os模塊判定文件的相關(guān)技巧,非常簡(jiǎn)單實(shí)用,需要的朋友可以參考下
    2015-07-07
  • Pytorch測(cè)試神經(jīng)網(wǎng)絡(luò)時(shí)出現(xiàn) RuntimeError:的解決方案

    Pytorch測(cè)試神經(jīng)網(wǎng)絡(luò)時(shí)出現(xiàn) RuntimeError:的解決方案

    這篇文章主要介紹了Pytorch測(cè)試神經(jīng)網(wǎng)絡(luò)時(shí)出現(xiàn) RuntimeError:的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • Python Socket TCP雙端聊天功能實(shí)現(xiàn)過程詳解

    Python Socket TCP雙端聊天功能實(shí)現(xiàn)過程詳解

    這篇文章主要介紹了Python Socket TCP雙端聊天功能實(shí)現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06

最新評(píng)論