Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Paramiko - Run command

I'm try to run this script:

hostname = '192.168.3.4'
port = 22
username = 'username'
password = 'mypassword'
y = "2012"
m = "02"
d = "27"

if __name__ == "__main__":
   s = paramiko.SSHClient()
   s.load_system_host_keys()
   s.connect(hostname, port, username, password)
   command = 'ls /home/user/images/cappi/03000/y/m/d'
   s.close

The question is: how can I put the variables y,m,d into the variable command ?

like image 467
marcelorodrigues Avatar asked Feb 27 '12 18:02

marcelorodrigues


People also ask

How do I get command output in Paramiko?

You can get the output the command by using stdout. read() (returns a string) or stdout. readlines() (returns a list of lines).

How do I use Paramiko in python?

A Paramiko SSH Example: Connect to Your Server Using a Password. This section shows you how to authenticate to a remote server with a username and password. To begin, create a new file named first_experiment.py and add the contents of the example file. Ensure that you update the file with your own Linode's details.

How do I run a python command on a remote server?

Executing Scriptsexec_command() method executes the script using the default shell (BASH, SH, or any other) and returns standard input, standard output, and standard error, respectively. We will read from stdout and stderr if there are any, and then we close the SSH connection.

What is Paramiko SSHClient ()?

SSHClient. A high-level representation of a session with an SSH server. This class wraps Transport , Channel , and SFTPClient to take care of most aspects of authenticating and opening channels. A typical use case is: client = SSHClient() client.


1 Answers

Python has lots of ways to perform string formatting. One of the simplest is to simply concatenate the parts of your string together:

#!/usr/bin/env python
hostname = '192.168.3.4'    
port = 22
username = 'username'
password = 'mypassword'
y = "2012"
m = "02"
d = "27"

def do_it():
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.connect(hostname, port, username, password)
    command = 'ls /home/user/images/cappi/03000/' + y + '/' + m + '/' + d
    (stdin, stdout, stderr) = s.exec_command(command)
    for line in stdout.readlines():
        print line
    s.close()

if __name__ == "main":
    do_it()
like image 145
mattbornski Avatar answered Oct 03 '22 02:10

mattbornski