Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticate with private key using Paramiko Transport (channel)

I'm trying to use Paramiko to open (and maintain) a channel so that I can issue a few commands; however, I'm unable to find an example using paramiko.Transport AND using a private key. I have been able to connect to my server and just run a command using the following code:

    ssh = paramiko.SSHClient()
    paramiko.util.log_to_file("support_scripts.log")
    private_key = paramiko.RSAKey.from_private_key_file(rsa_private_key)
    ssh.connect(server, username=user, password='', pkey=private_key)
    ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd)

No problems there. From what I understand, that doesn't create an "interactive session", meaning I can't issue cd /home/my_user/my_scripts and then issue another command like python script_in_my_scripts_folder.py. Therefore, I'm trying to use the Paramiko Transport object which can help me maintain an interactive session. Searching high and low, none of the examples I've found work for me. Right now, the following code returns "SSHException: Channel is not open" on line 204, which is the exec_command below:

    PRIVATEKEY = '/home/my_user/.ssh/id_rsa'
    user = 'harperville'
    server = '10.0.10.10'
    port = 22
    paramiko.util.log_to_file("support_scripts.log")
    trans = paramiko.Transport((server,port))
    rsa_key = paramiko.RSAKey.from_private_key_file(PRIVATEKEY)
    trans.connect(username=user, pkey=rsa_key)
    session = trans.open_channel("session")
    session.exec_command('cd /home/harperville/my_scripts/')

I understand the gist of what it's telling me but I can't find or understand the documentation to help me get past this problem.

Thanks in advance.

like image 517
harperville Avatar asked Oct 22 '22 16:10

harperville


1 Answers

I have found the issue with help from this site: http://j2labs.tumblr.com/post/4477180133/ssh-with-pythons-paramiko

If I change:

session = trans.open_channel("session")

to:

session = trans.open_session()

Then, I am allowed to run a command using:

session.exec_command('cd /home/harperville/my_scripts/')
like image 157
harperville Avatar answered Oct 29 '22 22:10

harperville