溫馨提示×

Ubuntu系統(tǒng)中Paramiko怎么配置

小樊
81
2024-09-27 06:01:09
欄目: 智能運維

在Ubuntu系統(tǒng)中配置Paramiko,主要涉及到安裝Paramiko庫以及設置SSH密鑰對進行身份驗證。以下是詳細的步驟:

安裝Paramiko

  1. 打開終端(Terminal)。

  2. 輸入以下命令來更新軟件包列表:

    sudo apt-get update
    
  3. 接下來,使用以下命令安裝Paramiko庫:

    sudo apt-get install python3-paramiko
    

配置和使用Paramiko

  1. 創(chuàng)建SSH密鑰對(如果尚未創(chuàng)建):

    • 在終端中輸入以下命令來生成一個新的SSH密鑰對:

      ssh-keygen -t rsa
      

      這將在你的用戶目錄下的.ssh文件夾中生成一個名為id_rsa(私鑰)和id_rsa.pub(公鑰)的文件。

  2. 將公鑰添加到遠程服務器

    • 使用以下命令復制公鑰到遠程服務器的~/.ssh/authorized_keys文件中(請確保替換<username><remote-server-ip>為實際的用戶名和遠程服務器IP地址):

      ssh-copy-id <username>@<remote-server-ip>
      

      輸入遠程服務器的密碼后,你的公鑰就會被添加到遠程服務器的授權密鑰列表中。

  3. 使用Paramiko進行SSH連接

    • 在Python腳本中,你可以使用以下代碼來建立SSH連接并使用私鑰進行身份驗證(請確保已安裝Paramiko庫):

      import paramiko
      
      # 創(chuàng)建SSH客戶端
      client = paramiko.SSHClient()
      
      # 設置一個默認的策略來接受不在本地known_hosts文件中的主機密鑰
      client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
      
      # 使用私鑰連接到SSH服務器
      private_key = paramiko.RSAKey.from_private_key_file('/path/to/your/id_rsa')
      client.connect('hostname', username='username', pkey=private_key)
      
      # 執(zhí)行命令
      stdin, stdout, stderr = client.exec_command('ls')
      
      # 獲取命令輸出
      output = stdout.read().decode('utf-8')
      error_output = stderr.read().decode('utf-8')
      
      # 關閉連接
      client.close()
      
      print('Output:', output)
      if error_output:
          print('Error:', error_output)
      

      請確保將/path/to/your/id_rsa替換為你實際的私鑰文件路徑,并根據需要更改主機名、用戶名和要執(zhí)行的命令。

通過以上步驟,你應該能夠在Ubuntu系統(tǒng)中成功配置并使用Paramiko進行SSH連接。

0