Tiếp series lập trình Python, xin giới thiệu với các bạn đoạn code Python 3 sau sử dụng thư viện paramiko có nhiệm vụ kết nối SSH tới 1 Remote Linux Server và chạy command “cat /etc/*-release” trên đó.
Kết nối SSH và chạy command sử dụng Python 3
import paramiko
ssh = paramiko.SSHClient()
# Auto add host to known hosts
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect to server
ssh.connect("192.168.2.100", username="root", password="123456")
# Do command
(ssh_stdin, ssh_stdout, ssh_stderr) = ssh.exec_command("cat /etc/*-release")
# Get status code of command
exit_status = ssh_stdout.channel.recv_exit_status()
# Print status code
print ("exit status: %s" % exit_status)
# Print content
for line in ssh_stdout.readlines():
print(line.rstrip())
# Close ssh connect
ssh.close()
Kết quả chạy thử:

Cài đặt paramiko module cho Python 3
Để chạy đoạn code trên cần cài đặt Python Module/Package là paramiko, chúng ta cài thông qua pip3
pip3 install paramiko
Khắc phục một số lỗi khi cài đặt paramiko
Fix lỗi:
CryptographyDeprecationWarning: encode_point has been deprecated on EllipticCurvePublicNumbers and will be removed in a future version. Please use EllipticCurvePublicKey.public_bytes to obtain both compressed and uncompressed point encoding.
pip3 install cryptography==2.4.2
Nguồn: vinasupport.com