Latest Post

Tăng thứ hạng và truy cập tự nhiên với 10 phương pháp SEO hay nhất Kiếm Tiền Online (mmo): Khái Niệm và Các Hình Thức Phổ Biến

Chào các bạn, tiếp tục trong chuỗi bài viết về lập trình Python, tôi xin giới thiệu một đoạn mã Python 3 sử dụng thư viện paramiko. Nhiệm vụ của đoạn mã này là thiết lập kết nối SSH tới một máy chủ Linux từ xa và thực hiện lệnh “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

Để thực hiện đoạn mã này, bạn cần cài đặt một Python Module/Package gọi là “paramiko.” Bạn có thể dùng lệnh sau để cài đặt nó 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

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *