Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การรันคำสั่งต่างๆ ผ่าน SSH ใน Python (Paramiko exec_command)

ใช้ Paramiko เดียวกับบทก่อนหน้า แต่เน้นการ รันหลายคำสั่ง ผ่าน SSH Connection เดียว

การเชื่อมต่อ (เหมือนเดิม)

from paramiko import SSHClient

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('user@server:path')

รันคำสั่งหลายคำสั่ง

# คำสั่งเดี่ยว
stdin, stdout, stderr = ssh.exec_command('ls -la')
print(stdout.read().decode())

# คำสั่งหลายบรรทัด (Multi-line command)
stdin, stdout, stderr = ssh.exec_command('''
    cd /home/user
    ls -la
    pwd
    whoami
''')
print(stdout.read().decode())

# รันคำสั่งต่อเนื่อง (เก็บ session ไว้)
commands = ['ls', 'pwd', 'whoami', 'df -h']
for cmd in commands:
    stdin, stdout, stderr = ssh.exec_command(cmd)
    print(f'=== {cmd} ===')
    print(stdout.read().decode())
    if stderr.channel.recv_exit_status() != 0:
        print(f'Error: {stderr.read().decode()}')

Interactive Shell (Invoke Shell)

>> channel = ssh.invoke_shell()
>>> channel.send('ls\n')
>>> time.sleep(0.5)
>>> print(channel.recv(4096).decode())

ข้อควรระวัง: exec_command สร้าง channel ใหม่ทุกครั้ง ไม่ share environment variables ระหว่างคำสั่ง ใช้ invoke_shell สำหรับ interactive session

ปิดการเชื่อมต่อ

ssh.close()