How to install and use Paramiko in Python?

To install paramiko, you can use the pip command. Run the following command in the terminal:

pip install paramiko

Once the installation is complete, you can use the paramiko library in your Python code.

Here is an example using the paramiko library:

import paramiko

# 创建SSH客户端
client = paramiko.SSHClient()
# 自动添加主机名和密钥到本地“known_hosts”文件中
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接SSH服务器
client.connect(hostname='your_host', port=22, username='your_username', password='your_password')

# 执行远程命令
stdin, stdout, stderr = client.exec_command('ls -l')
# 获取命令输出结果
output = stdout.read().decode('utf-8')
print(output)

# 关闭SSH连接
client.close()

In the example above, we start by creating an SSH client object and setting a policy to automatically add the hostname and key to the local “known_hosts” file. We then connect to the SSH server using the connect method and execute a remote command using the exec_command method. Finally, we close the SSH connection.

In addition, paramiko also offers other features such as file upload and download. You can refer to the official paramiko documentation for more information: https://docs.paramiko.org/

广告
Closing in 10 seconds
bannerAds