Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python paramiko module using multiple commands

I have a class that creates the connection. I can connect and execute 1 command before the channel is closed. On another system i have i can execute multiple commands and the channel does not close. Obviously its a config issue with the systems i am trying to connect to.

class connect:

    newconnection = ''

    def __init__(self,username,password): 
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect('somehost', username=username,password=password,port=2222,timeout=5)
        except:
            print "Count not connect"
            sys.exit()
        self.newconnection = ssh

    def con(self):
        return self.newconnection

Then i use 'ls' command just to print some output

sshconnection = connect('someuser','somepassword').con()


stdin, stdout, stderr = sshconnection.exec_command("ls -lsa")

print stdout.readlines() 
print stdout 

stdin, stdout, stderr = sshconnection.exec_command("ls -lsa")

print stdout.readlines() 
print stdout 

sshconnection.close()
sys.exit()

After the first exec_command runs it prints the expected output of the dir list. When i print stdout after the first exec_command it looks like the channel is closed

<paramiko.ChannelFile from <paramiko.Channel 1 (closed) -> <paramiko.Transport at 0x2400f10L (cipher aes128-ctr, 128 bits) (active; 0 open channel(s))>>> 

Like i said on another system i am able to keep running commands and the connection doesn't close. Is there a way i can keep this open? or a better way i can see the reason why it closes?

edit: So it looks like you can only run 1 command per SSHClient.exec_command... so i decided to get_transport().open_session() and then run a command. The first one always works. The second one always fails and the scripts just hangs

like image 396
rubio Avatar asked Feb 14 '23 19:02

rubio


1 Answers

With just paramiko after the exec_command executes the channel is closed and the ssh returns an auth prompt.

Seems its not possible with just paramiko, try fabric or another tool.

** fabric did not work out too.

like image 113
rubio Avatar answered Feb 17 '23 10:02

rubio