How do you execute multiple commands in a single session in Paramiko? (Python)

前端 未结 6 1201
礼貌的吻别
礼貌的吻别 2020-11-27 13:50
def exec_command(self, command, bufsize=-1):
    #print \"Executing Command: \"+command
    chan = self._transport.open_session()
    chan.exec_command(command)
             


        
6条回答
  •  死守一世寂寞
    2020-11-27 14:23

    You can execute an entire BASH script file for better use, here is the code for that:

    import paramiko
    
    hostname = "192.168.1.101"
    username = "test"
    password = "abc123"
    
    # initialize the SSH client
    client = paramiko.SSHClient()
    # add to known hosts
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        client.connect(hostname=hostname, username=username, password=password)
    except:
        print("[!] Cannot connect to the SSH Server")
        exit()
    
    # read the BASH script content from the file
    bash_script = open("script.sh").read()
    # execute the BASH script
    stdin, stdout, stderr = client.exec_command(bash_script)
    # read the standard output and print it
    print(stdout.read().decode())
    # print errors if there are any
    err = stderr.read().decode()
    if err:
        print(err)
    # close the connection
    client.close()
    

    This will execute the local script.sh file on the remote 192.168.1.101 Linux machine.

    script.sh (just an example):

    cd Desktop
    mkdir test_folder
    cd test_folder
    echo "$PATH" > path.txt
    

    This tutorial explains this in detail: How to Execute BASH Commands in a Remote Machine in Python.

提交回复
热议问题