Search code examples
pythonsubprocessfabricparamikopexpect

SSH a linux box using subprocess module


I have a requirement where i need to do the following

I need to ssh to a linux box , run a command , get the output back and i need to do some manipulations.

Is that possible via python subprocess module.

Basically i need a .py code in which i will give the ip address, username and password for connecting to the linux box and run a command and get the output.

Also is that possible via any other modules available in Python.

Suggestions are welcome.


Solution

  • Your question is tagged with "paramiko", so why don't you just use that?

    I need to ssh to a linux box , run a command , get the output back and i need to do some manipulations.

    ssh to a linux box (or any other ssh server):

    >>> import paramiko
    >>> ssh=paramiko.SSHClient()
    >>> ssh.load_system_host_keys()
    >>> ssh.connect(hostname='localhost', username='haiprasan86', password='secret')
    >>> print ssh
    <paramiko.SSHClient object at 0xdf2590>
    

    run a command:

    >>> _, out, err = ssh.exec_command('ls -l /etc/passwd')
    >>> # block until remote command completes
    >>> status = out.channel.recv_exit_status()
    >>> print status
    0
    

    get the output back:

    >>> print out.readlines()
    ['-rw-r--r--. 1 root root 2351 Mar 27 10:57 /etc/passwd\n']
    

    I don't know what manipulations you want to do.