211

I'm writing a script to automate some command line commands in Python. At the moment, I'm doing calls like this:

cmd = "some unix command"
retcode = subprocess.call(cmd,shell=True)

However, I need to run some commands on a remote machine. Manually, I would log in using ssh and then run the commands. How would I automate this in Python? I need to log in with a (known) password to the remote machine, so I can't just use cmd = ssh user@remotehost, I'm wondering if there's a module I should be using?

Milan
  • 1,743
  • 2
  • 13
  • 36
fredley
  • 32,953
  • 42
  • 145
  • 236
  • Does this answer your question? [python libraries for ssh handling](https://stackoverflow.com/questions/1939107/python-libraries-for-ssh-handling) – miken32 Aug 27 '20 at 00:08
  • 2
    Have you had a look at [Fabric](http://www.fabfile.org)? It allows you to do all sorts of remote stuff over SSH using python. – tomaski Aug 27 '10 at 16:16
  • Here is a simple wrapper class for `subprocess` calling `ssh`: https://gist.github.com/mamaj/a7b378a5c969e3e32a9e4f9bceb0c5eb – mamaj Aug 25 '22 at 16:34
  • I have used paramiko a bunch (nice) and pxssh (also nice). I would recommend either. They work a little differently but have a relatively large overlap in usage. – Eric Snow Aug 27 '10 at 17:25

17 Answers17

278

I will refer you to paramiko

see this question

ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)

If you are using ssh keys, do:

k = paramiko.RSAKey.from_private_key_file(keyfilename)
# OR k = paramiko.DSSKey.from_private_key_file(keyfilename)

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=user, pkey=k)
vvvvv
  • 25,404
  • 19
  • 49
  • 81
shahjapan
  • 13,637
  • 22
  • 74
  • 104
  • 1
    @R-Dit, for ssh keys, try getting rid of the password parameter and run the following command before connecting: `ssh.load_system_host_keys()`. – alfonso Sep 14 '16 at 19:23
  • 10
    As a long-time user of Paramiko (but not an expert), I can suggest using Paramiko but you should consider your use cases and how much you're willing to learn. Paramiko is very low-level, and you can easily fall into a trap where you create a "command running helper function" without fully understanding the code you're using. That means you might design say a `def run_cmd(host, cmd):` which does what you want at first, but your needs evolve. You end up changing the helper for the new use case, which changes behavior of the older existing usage. Plan accordingly. – Scott Prive Apr 20 '17 at 14:27
  • There is also this list of SSH wrappers in the Python wiki: https://wiki.python.org/moin/SecureShell It is a little out of date, as it omits python-executor (https://pypi.python.org/pypi/executor) – Scott Prive Apr 20 '17 at 14:29
  • 7
    For unknown host error, do: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) before – Nemo Jan 22 '19 at 08:16
  • whats wrong with ssh ?... User subprocess to invoke. See answer below. – Ronn Macc Aug 10 '19 at 05:51
  • @RonnMacc new connection for each command? – MrR Apr 14 '22 at 12:51
  • @MrR - Yes. Should be okay for most cases. You can build a set of commands (using semicolons) (or script) and invoke in one go. – Ronn Macc Apr 22 '22 at 02:38
  • 1
    A few seconds to connect for each command may easily be NOT ok. – MrR Apr 22 '22 at 23:30
  • what is "keyfilename" value? is it the path the private ssh key file? eg ~/.ssh/id_rsa ? – majorgear May 29 '22 at 00:48
83

Keep it simple. No libraries required.

import subprocess

# Python 2
subprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

# Python 3
subprocess.Popen(f"ssh {user}@{host} {cmd}", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
Ronn Macc
  • 1,271
  • 9
  • 7
  • 4
    Subprocess is your swiss army knife in automation. You can then combine Python with endless possibilities like shell scripts, sed, awk, grep. Yes you can all do in Python, but wouldnt it be great to just run a grep somewhere in python - well you can. – Ronn Macc Jan 31 '20 at 14:47
  • 29
    if your ssh commands asks for password how would you provide that in Python file ? – BeingSuman Feb 06 '20 at 11:09
  • 3
    @BeingSuman You can use SSH key authentication for that. Though I guess You already have figured that out. – mmrbulbul May 15 '20 at 07:47
  • 1
    "you can use ssh key" sounds as excuse to the sub process way, more over - god help you if you access the ssh remote first time or ECDSA key didn't match. Not considering even the efficiency of creating new connection each time for new command. it's more "Keep it simple. Be limited", you don't even need python - do the stuff with bash script – Reishin Jan 23 '21 at 23:21
  • 5
    You can also use "sshpass -p {password} ssh {user}@{ip}" – Carsten Jan 06 '22 at 10:37
  • 2
    @BeingSuman `f"echo {password} | ssh {user}@{host} {cmd}"`. Only secure if user is prompted, of course. – Gulzar Mar 01 '22 at 15:22
  • @Reishin you can ignore warnings on keys with ssh flags. – MrR Apr 14 '22 at 12:47
  • 1
    New connection for each command is bad. – MrR Apr 14 '22 at 12:49
  • @MrR my point was - if you use `Popen`, better use bash scripting instead of python in current particular situation – Reishin Apr 17 '22 at 05:40
  • 1
    Maybe. We like our python. – MrR Apr 22 '22 at 23:29
  • 1
    Here is a simple wrapper class for `subprocess` calling `ssh`: https://gist.github.com/mamaj/a7b378a5c969e3e32a9e4f9bceb0c5eb – mamaj Aug 25 '22 at 16:32
  • 1
    @mamaj Looks good. Pls do add ability to return stdout / stderr. My fav part is to use combinations of head/tail/cut/sed/awk/grep/sort/uniq/tr and consume the output in python. – Ronn Macc Aug 26 '22 at 06:18
  • @BeingSuman - check "sshpass" – Ronn Macc Oct 12 '22 at 06:35
  • upvoted for ease. But it's not optimal if you want to execute multiple commands (and parse their output invidiually) – gebbissimo Mar 10 '23 at 05:23
58

Or you can just use commands.getstatusoutput:

commands.getstatusoutput("ssh machine 1 'your script'")

I used it extensively and it works great.

In Python 2.6+, use subprocess.check_output.

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
powerrox
  • 1,334
  • 11
  • 21
  • 8
    +1 for a nice simple built-in method. In my current setup I do not want to be adding Python libraries so your suggestion is valuable, very straightforward too. – Philip Kearns Nov 26 '13 at 09:26
  • 4
    just make sure your remote host is setup for passwordless ssh, if not, you have to do other things for managing authentication – powerrox Jun 17 '14 at 21:12
  • subprocess.check_output -- great solution! – Tim S. Sep 08 '15 at 21:52
  • 2
    @powerrox what are those "other things?" – ealeon Nov 30 '15 at 05:45
  • 2
    @TimS. you may have to include handling for authentication by whatever means is appropriate for your setup. I used expect to enter password at the prompt. then there is this thread with other solutions: http://unix.stackexchange.com/questions/147329/answer-password-prompt-programmatically-via-shell-script – powerrox Dec 01 '15 at 16:22
  • 1
    Note that the `commands` module has been removed in Python 3. Use the `subprocess` module instead as mentioned in another answer here. – Dylan Hogg Oct 18 '21 at 11:11
22

I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called spur that uses paramiko to implement a slightly nicer interface:

import spur

shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello

If you need to run inside a shell:

shell.run(["sh", "-c", "echo -n hello"])
Michael Williamson
  • 11,308
  • 4
  • 37
  • 33
  • 2
    I decided to try `spur`. You generate additional shell commands and you end up with: which 'mkdir' > /dev/null 2>&1 ; echo $?; exec 'mkdir' '-p' '/data/rpmupdate/20130207142923'. I would like to have also access to a plain `exec_command`. Also missing ability to run background tasks: `nohup ./bin/rpmbuildpackages < /dev/null >& /dev/null &`. E.g., I generate a zsh script (rpmbuildpackages) using template and then I just to leave it running on the machine. Maybe ability to monitor such background jobs also would be nice (saving PIDs in some ~/.spur). – davidlt Feb 07 '13 at 13:55
  • 1
    `spur` apparently only works on unix systems cause it has a dependency on [`termios`](http://docs.python.org/2/library/termios.html). Does anybody know a good library for Windows? – Gabriel Jun 05 '13 at 01:25
  • Not entirely true: if you use a [precompiled installer](http://www.voidspace.org.uk/python/modules.shtml#pycrypto), you will be able to install paramiko and spur. I just did it myself... – ravemir Mar 12 '14 at 16:58
  • @Gabriel: one of the recent releases should have improved support on Windows. If it's still not working, please feel free to open an issue. – Michael Williamson Aug 25 '14 at 14:02
  • @davidlt: when constructing an `SshShell`, there is now the option to set the shell type. If a minimal shell is used by passing in `shell_type=spur.ssh.ShellTypes.minimal`, then only the raw command is sent. Implementing background tasks directly feels a bit out of scope for Spur, but you should be able to run the command you've described by invoking a shell e.g. `shell.run(["sh", "-c", "nohup ./bin/rpmbuildpackages < /dev/null >& /dev/null &"]`). – Michael Williamson Aug 25 '14 at 14:04
11

All have already stated (recommended) using paramiko and I am just sharing a python code (API one may say) that will allow you to execute multiple commands in one go.

to execute commands on different node use : Commands().run_cmd(host_ip, list_of_commands)

You will see one TODO, which I have kept to stop the execution if any of the commands fails to execute, I don't know how to do it. please share your knowledge

#!/usr/bin/python

import os
import sys
import select
import paramiko
import time


class Commands:
    def __init__(self, retry_time=0):
        self.retry_time = retry_time
        pass

    def run_cmd(self, host_ip, cmd_list):
        i = 0
        while True:
        # print("Trying to connect to %s (%i/%i)" % (self.host, i, self.retry_time))
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(host_ip)
            break
        except paramiko.AuthenticationException:
            print("Authentication failed when connecting to %s" % host_ip)
            sys.exit(1)
        except:
            print("Could not SSH to %s, waiting for it to start" % host_ip)
            i += 1
            time.sleep(2)

        # If we could not connect within time limit
        if i >= self.retry_time:
            print("Could not connect to %s. Giving up" % host_ip)
            sys.exit(1)
        # After connection is successful
        # Send the command
        for command in cmd_list:
            # print command
            print "> " + command
            # execute commands
            stdin, stdout, stderr = ssh.exec_command(command)
            # TODO() : if an error is thrown, stop further rules and revert back changes
            # Wait for the command to terminate
            while not stdout.channel.exit_status_ready():
                # Only print data if there is data to read in the channel
                if stdout.channel.recv_ready():
                    rl, wl, xl = select.select([ stdout.channel ], [ ], [ ], 0.0)
                    if len(rl) > 0:
                        tmp = stdout.channel.recv(1024)
                        output = tmp.decode()
                        print output

        # Close SSH connection
        ssh.close()
        return

def main(args=None):
    if args is None:
        print "arguments expected"
    else:
        # args = {'<ip_address>', <list_of_commands>}
        mytest = Commands()
        mytest.run_cmd(host_ip=args[0], cmd_list=args[1])
    return


if __name__ == "__main__":
    main(sys.argv[1:])
Adriaan
  • 17,741
  • 7
  • 42
  • 75
IAmSurajBobade
  • 353
  • 6
  • 15
  • Just use multiprocessing and kill the process if it takes too much time. On the other side it's a problem though, you could put a timeout there too I guess? – Ajay Nov 12 '21 at 11:51
10

The accepted answer didn't work for me, here's what I used instead:

import paramiko
import os

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# ssh.load_system_host_keys()
ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
ssh.connect("d.d.d.d", username="user", password="pass", port=22222)

ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("ls -alrt")
exit_code = ssh_stdout.channel.recv_exit_status() # handles async exit error 

for line in ssh_stdout:
    print(line.strip())

total 44
-rw-r--r--.  1 root root  129 Dec 28  2013 .tcshrc
-rw-r--r--.  1 root root  100 Dec 28  2013 .cshrc
-rw-r--r--.  1 root root  176 Dec 28  2013 .bashrc
...

Alternatively, you can use sshpass:

import subprocess
cmd = """ sshpass -p "myPas$" ssh user@d.d.d.d -p 12345 'my command; exit' """
print( subprocess.getoutput(cmd) )

References:

  1. https://github.com/onyxfish/relay/issues/11
  2. https://stackoverflow.com/a/61016663/797495

Notes:

  1. Just make sure to connect manually at least one time to the remote system via ssh (ssh root@ip) and accept the public key, this is many times the reason from not being able connect using paramiko or other automated ssh scripts.
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
9

paramiko finally worked for me after adding additional line about allowing missing host key policy, which is really important one (line 5):

import paramiko

p = paramiko.SSHClient()
# This script doesn't work for me unless the following line is added!
p.set_missing_host_key_policy(paramiko.AutoAddPolicy())   
p.connect("server", port=22, username="username", password="password")
stdin, stdout, stderr = p.exec_command("your command")
opt = stdout.readlines()
opt = "".join(opt)
print(opt)

Make sure that paramiko package is installed. Original source of the solution: Source

A.L
  • 10,259
  • 10
  • 67
  • 98
3

First: I'm surprised that no one has mentioned fabric yet.

Second: For exactly those requirements you describe I've implemented an own python module named jk_simpleexec. It's purpose: Making running commands easy.

Let me explain a little bit about it for you.

The 'executing a command locally' problem

My python module jk_simpleexec provides a function named runCmd(..) that can execute a shell (!) command locally or remotely. This is very simple. Here is an example for local execution of a command:

import jk_simpleexec

cmdResult = jk_simpleexec.runCmd(None, "cd / ; ls -la")

NOTE: Be aware that the returned data is trimmed automatically by default to remove excessive empty lines from STDOUT and STDERR. (Of course this behavior can be deactivated, but for the purpose you've in mind exactly that behavior is what you will want.)

The 'processing the result' problem

What you will receive is an object that contains the return code, STDOUT and STDERR. Therefore it's very easy to process the result.

And this is what you want to do as the command you execute might exist and is launched but might fail in doing what it is intended to do. In the most simple case where you're not interested in STDOUT and STDERR your code will likely look something like this:

cmdResult.raiseExceptionOnError("Something went wrong!", bDumpStatusOnError=True)

For debugging purposes you want to output the result to STDOUT at some time, so for this you can do just this:

cmdResult.dump()

If you would want to process STDOUT it's simple as well. Example:

for line in cmdResult.stdOutLines:
    print(line)

The 'executing a command remotely' problem

Now of course we might want to execute this command remotely on another system. For this we can use the same function runCmd(..) in exactly the same way but we need to specify a fabric connection object first. This can be done like this:

from fabric import Connection

REMOTE_HOST = "myhost"
REMOTE_PORT = 22
REMOTE_LOGIN = "mylogin"
REMOTE_PASSWORD = "mypwd"
c = Connection(host=REMOTE_HOST, user=REMOTE_LOGIN, port=REMOTE_PORT, connect_kwargs={"password": REMOTE_PASSWORD})

cmdResult = jk_simpleexec.runCmd(c, "cd / ; ls -la")

# ... process the result stored in cmdResult ...

c.close()

Everything remains exactly the same, but this time we run this command on another host. This is intended: I wanted to have a uniform API where there are no modifications required in the software if you at some time decide to move from the local host to another host.

The password input problem

Now of course there is the password problem. This has been mentioned above by some users: We might want to ask the user executing this python code for a password.

For this problem I have created an own module quite some time ago. jk_pwdinput. The difference to regular password input is that jk_pwdinput will output some stars instead of just printing nothing. So for every password character you type you will see a star. This way it's more easy for you to enter a password.

Here is the code:

import jk_pwdinput

# ... define other 'constants' such as REMOTE_LOGIN, REMOTE_HOST ...

REMOTE_PASSWORD = jk_pwdinput.readpwd("Password for " + REMOTE_LOGIN + "@" + REMOTE_HOST + ": ")

(For completeness: If readpwd(..) returned None the user canceled the password input with Ctrl+C. In a real world scenario you might want to act on this appropriately.)

Full example

Here is a full example:

import jk_simpleexec
import jk_pwdinput
from fabric import Connection

REMOTE_HOST = "myhost"
REMOTE_PORT = 22
REMOTE_LOGIN = "mylogin"
REMOTE_PASSWORD = jk_pwdinput.readpwd("Password for " + REMOTE_LOGIN + "@" + REMOTE_HOST + ": ")
c = Connection(host=REMOTE_HOST, user=REMOTE_LOGIN, port=REMOTE_PORT, connect_kwargs={"password": REMOTE_PASSWORD})

cmdResult = jk_simpleexec.runCmd(
    c = c,
    command = "cd / ; ls -la"
)
cmdResult.raiseExceptionOnError("Something went wrong!", bDumpStatusOnError=True)

c.close()

Final notes

So we have the full set:

  • Executing a command,
  • executing that command remotely via the same API,
  • creating the connection in an easy and secure way with password input.

The code above solves the problem quite well for me (and hopefully for you as well). And everything is open source: Fabric is BSD-2-Clause, and my own modules are provided under Apache-2.

Modules used:

Happy coding! ;-)

Regis May
  • 3,070
  • 2
  • 30
  • 51
1

Works Perfectly...

import paramiko
import time

ssh = paramiko.SSHClient()
#ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.106.104.24', port=22, username='admin', password='')

time.sleep(5)
print('connected')
stdin, stdout, stderr = ssh.exec_command(" ")

def execute():
       stdin.write('xcommand SystemUnit Boot Action: Restart\n')
       print('success')

execute()
Community
  • 1
  • 1
Harshan Gowda
  • 181
  • 2
  • 10
1

You can use any of these commands, this will help you to give a password also.

cmd = subprocess.run(["sshpass -p 'password' ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@domain.com ps | grep minicom"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(cmd.stdout)
OR
cmd = subprocess.getoutput("sshpass -p 'password' ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@domain.com ps | grep minicom")
print(cmd)
Sachin Rastogi
  • 409
  • 5
  • 8
0

Have a look at spurplus, a wrapper we developed around spur that provides type annotations and some minor gimmicks (reconnecting SFTP, md5 etc.): https://pypi.org/project/spurplus/

marko.ristin
  • 643
  • 8
  • 6
  • 5
    a wrapper around a wrapper around a wrapper .. nice :) – Alex R Jun 27 '19 at 12:24
  • Well, if you want to keep your deployment scripts trivial, I doubt that the underlying tools are simple/abstract enough. So far, we didn't observe leaky abstractions. – marko.ristin Jun 28 '19 at 13:09
0
#Reading the Host,username,password,port from excel file
import paramiko 
import xlrd

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

loc = ('/Users/harshgow/Documents/PYTHON_WORK/labcred.xlsx')
wo = xlrd.open_workbook(loc)
sheet = wo.sheet_by_index(0)
Host = sheet.cell_value(0,1)
Port = int(sheet.cell_value(3,1))
User = sheet.cell_value(1,1)
Pass = sheet.cell_value(2,1)

def details(Host,Port,User,Pass):
    ssh.connect(Host, Port, User, Pass)
    print('connected to ip ',Host)
    stdin, stdout, stderr = ssh.exec_command("")
    stdin.write('xcommand SystemUnit Boot Action: Restart\n')
    print('success')

details(Host,Port,User,Pass)
barbsan
  • 3,418
  • 11
  • 21
  • 28
Harshan Gowda
  • 181
  • 2
  • 10
0

Asking User to enter the command as per the device they are logging in.
The below code is validated by PEP8online.com.

import paramiko
import xlrd
import time

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
loc = ('/Users/harshgow/Documents/PYTHON_WORK/labcred.xlsx')
wo = xlrd.open_workbook(loc)
sheet = wo.sheet_by_index(0)
Host = sheet.cell_value(0, 1)
Port = int(sheet.cell_value(3, 1))
User = sheet.cell_value(1, 1)
Pass = sheet.cell_value(2, 1)

def details(Host, Port, User, Pass):
    time.sleep(2)
    ssh.connect(Host, Port, User, Pass)
    print('connected to ip ', Host)
    stdin, stdout, stderr = ssh.exec_command("")
    x = input('Enter the command:')
    stdin.write(x)
    stdin.write('\n')
    print('success')

details(Host, Port, User, Pass)
Valentino
  • 7,291
  • 6
  • 18
  • 34
Harshan Gowda
  • 181
  • 2
  • 10
0

The most modern approach is probably to use fabric. This module allows you to set up an SSH connection and then run commands and get their results over the connection object.

Here's a simple example:

from fabric import Connection
with Connection("your_hostname") as connection:
    result = connection.run("uname -s", hide=True)
    msg = "Ran {0.command!r} on {0.connection.host}, got stdout:\n{0.stdout}"
    print(msg.format(result))
leosh
  • 878
  • 9
  • 22
0

I wrote a simple class to run commands on remote over native ssh, using the subprocess module:

Usage

from ssh_utils import SshClient
client = SshClient(user='username', remote='remote_host', key='path/to/key.pem')

# run a list of commands
client.cmd(['mkdir ~/testdir', 'ls -la', 'echo done!'])

# copy files/dirs
client.scp('my_file.txt', '~/testdir')

Class source code

https://gist.github.com/mamaj/a7b378a5c969e3e32a9e4f9bceb0c5eb

import subprocess
from pathlib import Path
from typing import Union

class SshClient():
    """ Perform commands and copy files on ssh using subprocess 
        and native ssh client (OpenSSH).
    """
    
    def __init__(self,
                 user: str,
                 remote: str,
                 key_path: Union[str, Path]) -> None:
        """

        Args:
            user (str): username for the remote
            remote (str): remote host IP/DNS
            key_path (str or pathlib.Path): path to .pem file
        """
        self.user = user
        self.remote = remote
        self.key_path = str(key_path)
        
        
    def cmd(self, 
            cmds: list[str],
            strict_host_key_checking=False) -> None:
        
        """runs commands consecutively, ensuring success of each
            after calling the next command.

        Args:
            cmds (list[str]): list of commands to run.
            strict_host_key_checking (bool, optional): Defaults to True.
        """
        
        strict_host_key_checking = 'yes' if strict_host_key_checking \
                                    else 'no'
        cmd = ' && '.join(cmds)
        subprocess.run(
            [
                'ssh',
                '-i', self.key_path,
                '-o', f'StrictHostKeyChecking={strict_host_key_checking}', 
                '-o', 'UserKnownHostsFile=/dev/null',
                f'{self.user}@{self.remote}', 
                cmd
            ]
        )
        
        
    def scp(self, source: Union[str, Path], destination: Union[str, Path]):
        """Copies `srouce` file to remote `destination` using the 
            native `scp` command.
            
        Args:
            source (Union[str, Path]): Source file path.
            destination (Union[str, Path]): Destination path on remote.
        """
        subprocess.run(
            [
                'scp',
                '-i', self.key_path,
                str(source), 
                f'{self.user}@{self.remote}:{str(destination)}',
            ]
        )


mamaj
  • 910
  • 8
  • 8
-1

sshpass is working for Linux only. sshpass is not present on the windows

-2

Below example, incase if you want user inputs for hostname,username,password and port no.

  import paramiko

  ssh = paramiko.SSHClient()

  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())



  def details():

  Host = input("Enter the Hostname: ")

  Port = input("Enter the Port: ")

  User = input("Enter the Username: ")

  Pass = input("Enter the Password: ")

  ssh.connect(Host, Port, User, Pass, timeout=2)

  print('connected')

  stdin, stdout, stderr = ssh.exec_command("")

  stdin.write('xcommand SystemUnit Boot Action: Restart\n')

  print('success')

  details()
Zain Farooq
  • 2,956
  • 3
  • 20
  • 42
Harshan Gowda
  • 181
  • 2
  • 10
  • 8
    Rather than reposting your answer from two days ago with better formatting, why not edit the older answer and improve its formatting? – snakecharmerb May 13 '19 at 16:45