python 連接linux服務器


import paramiko


class Monitor(object):
    def __init__(self, server_ip, user, pwd):
        """ 初始化ssh客戶端 """
        try:
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.client = client
            print('------------開始連接服務器(%s)-----------' % server_ip)
            self.client.connect(server_ip, 22, username=user, password=pwd, timeout=4)
            print('------------認證成功!.....-----------')
        except Exception:
            print(f'連接遠程linux服務器(ip:{server_ip})發生異常!請檢查用戶名和密碼是否正確!')

    def link_server(self, cmd):
        """連接服務器發送命令"""
        try:
            stdin, stdout, stderr = self.client.exec_command(cmd)
            content = stdout.read().decode('gbk')
            return content
        except Exception as e:
            print('link_server-->返回命令發生異常,內容:', e)
        finally:
            self.client.close()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM