วิธีที่ง่ายที่สุดคือใช้ Library Paramiko (Pure Python SSH2 implementation)
ติดตั้ง
$ pip install paramiko
ข้อกำหนดก่อนใช้งาน
- ตั้งค่า SSH Keys บน Host Machine ให้ถูกต้อง
- เมื่อรันสคริปต์ ต้องเข้าถึง Private Key ได้
ตัวอย่างเชื่อมต่อและรันคำสั่ง
from paramiko import SSHClient
ssh = SSHClient()
ssh.load_system_host_keys() # โหลด known_hosts
ssh.connect('user@server:path') # หรือใช้ hostname, username, key_filename
stdin, stdout, stderr = ssh.exec_command('ls')
print(stdout.read().decode()) # พิมพ์ผลลัพธ์ ls
ssh.close()
ตัวอย่างแบบเต็ม (ใช้ Key File)
from paramiko import SSHClient, RSAKey
ssh = SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
private_key = RSAKey.from_private_key_file('/path/to/id_rsa')
ssh.connect(
hostname='example.com',
username='user',
pkey=private_key
)
stdin, stdout, stderr = ssh.exec_command('ls -la /home/user')
for line in stdout:
print(line.strip())
ssh.close()
หมายเหตุ: Paramiko รองรับ SSH2 เท่านั้น ไม่รองรับ SSH1