logo
down
shadow

Paramiko with subprocess


Paramiko with subprocess

By : Илья Вага
Date : October 24 2020, 06:10 AM
I hope this helps you . You cannot run a program on a remote server over SSH with subprocess.
Use SSHClient.exec_command to execute your command.
code :


Share : facebook icon twitter icon
Does paramiko close ssh connection on a non-paramiko exception

Does paramiko close ssh connection on a non-paramiko exception


By : Antonio
Date : March 29 2020, 07:55 AM
To fix this issue No, paramiko will not automatically close the ssh / sftp session. It doesn't matter if the exception was generated by paramiko code or otherwise; there is nothing in the paramiko code that catches any exceptions and automatically closes them, so you have to do it yourself.
You can ensure that it gets closed by wrapping it in a try/finally block like so:
code :
client = None
try:
    client = SSHClient()
    client.load_system_host_keys()
    client.connect('ssh.example.com')
    stdin, stdout, stderr = client.exec_command('ls -l')
finally:
    if client:
        client.close()
py2exe - paramiko, ImportError: No module named paramiko

py2exe - paramiko, ImportError: No module named paramiko


By : ahosein
Date : March 29 2020, 07:55 AM
With these it helps im trying to compile my application whit py2exe, setup.py code : , You need to put import paramiko into your setup.py as well.
Error in paramiko: paramiko.transport: TypeError: long() argument must be a string or a number, not 'NoneType'

Error in paramiko: paramiko.transport: TypeError: long() argument must be a string or a number, not 'NoneType'


By : user3071114
Date : March 29 2020, 07:55 AM
hope this fix your issue Please check that pkey actually contains your private key. If not, load it with
code :
pkey = paramiko.RSAKey.from_private_key_file("priv.key")
client.get_host_keys().add(hostname, 'ssh-rsa', peer_pubkey)
Paramiko: nest ssh session to another machine while preserving paramiko functionality (ProxyJump)

Paramiko: nest ssh session to another machine while preserving paramiko functionality (ProxyJump)


By : 30grams
Date : March 29 2020, 07:55 AM
help you fix your problem Update 15.05.18: added the missing code (copy-paste gods haven't been favorable to me).
TL;DR: I managed to do it using simple exec_command call and a class that pretends to be a sock.
code :
import paramiko
import time
import socket     
from select import select                                                       


class ParaProxy(paramiko.proxy.ProxyCommand):                      
    def __init__(self, stdin, stdout, stderr):                             
        self.stdin = stdin                                                 
        self.stdout = stdout                                               
        self.stderr = stderr
        self.timeout = None
        self.channel = stdin.channel                                               

    def send(self, content):                                               
        try:                                                               
            self.stdin.write(content)                                      
        except IOError as exc:                                             
            raise socket.error("Error: {}".format(exc))                                                    
        return len(content)                                                

    def recv(self, size):                                                  
        try:
            buffer = b''
            start = time.time()

            while len(buffer) < size:
                select_timeout = self._calculate_remaining_time(start)
                ready, _, _ = select([self.stdout.channel], [], [],
                                     select_timeout)
                if ready and self.stdout.channel is ready[0]:
                      buffer += self.stdout.read(size - len(buffer))

        except socket.timeout:
            if not buffer:
                raise

        except IOError as e:
            return ""

        return buffer

    def _calculate_remaining_time(self, start):
        if self.timeout is not None:
            elapsed = time.time() - start
            if elapsed >= self.timeout:
                raise socket.timeout()
            return self.timeout - elapsed
        return None                                   

    def close(self):                                                       
        self.stdin.close()                                                 
        self.stdout.close()                                                
        self.stderr.close()
        self.channel.close()                                                                                                                            
# Connecting to MiddleMachine and executing netcat
mid_cli = paramiko.SSHClient()
mid_cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
mid_cli.connect(hostname='1.1.1.1', username='user', password='pass')
io_tupple = mid_cli.exec_command('nc 2.2.2.2 22')

# Instantiate the 'masquerader' class
proxy = ParaProxy(*io_tupple)

# Connecting to AnotherMachine and executing... anything...
end_cli = paramiko.SSHClient()
end_cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
end_cli.connect(hostname='2.2.2.2', username='user', password='pass', sock=proxy)
end_cli.exec_command('echo THANK GOD FINALLY')
Use Paramiko's stdout as stdin with subprocess

Use Paramiko's stdout as stdin with subprocess


By : user6445272
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Yes, subprocess cannot redirect output on a "fake" file. It needs fileno which is defined only with "real" files (io.BytesIO() doesn't have it either).
I would do it manually like the following code demonstrates:
code :
proc = subprocess.Popen(['cat'], stdin=subprocess.PIPE)
proc.stdin.write(ssh_stdout.read())
proc.stdin.close()
Related Posts Related Posts :
  • Percent signs in windows path
  • How to add a random number to a subsection of a numpy array?
  • How to generate all the values of an iterable besides the last few?
  • Searching by both class and range in XPath
  • Python code execution in Perl interpreter
  • Best Way to Include Variable in Python3
  • Serialize the @property methods in a Python class
  • What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
  • Good way to edit the previous defined class in ipython
  • Bounced email on Google App Engine
  • Search jpeg files using python
  • Dynamically create class attributes
  • python unichr problem
  • Python beginner, strange output problem
  • Python: Finding a value in 1 list and finding that corresponding index in another list
  • can't install mysqlclient on mac os x mojave
  • Error indicates flattened dimensions when loading pre-trained network
  • how to replace underlines with words?
  • Adding through iteration
  • Use OpenCV on deployed Flask app (Heroku)
  • How to skip interstitial in a django view if a user hits the back button?
  • Any Naive Bayesian Classifier in python?
  • Python 2.5.2: remove what found between two lines that contain two concrete strings
  • Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory
  • HttpResponseRedirect question
  • Python socket error on UDP data receive. (10054)
  • Encoding issues with cloud ml
  • numpy.where - Weird behaviour: new elements spawning from nowhere?
  • I can't move my player in pygame, can you figure why?
  • Weird error I receive from Tkinter in Python
  • Using a Zapier Custom Request Webhook with JSON Web Tokens
  • Keras: Use categorical_crossentropy without one-hot encoded array of targets
  • Does python's httplib.HTTPConnection block?
  • Do alternate python implementation version numbers imply that they provide the same syntax?
  • Searching for specific HTML string using Python
  • python sax error "junk after document element"
  • MySql: How to know if an entry is compressed or not
  • Return a list of imported Python modules used in a script?
  • Returning a list in this recursive coi function in python
  • Python2.6 Decimal to Octal
  • Appengine Apps Vs Google bot web crawler
  • Changing models in django results in broken database?
  • Global variable functions
  • Using lambda inside a function
  • How to open a file, replace some strings, and save updates to the same file?
  • How to move the beginning of an input to the and?
  • If else fill variable if empty list
  • Pandas: Find and print all floats in column
  • sqlite3.OperationalError: database is locked - non-threaded application
  • How to implement mib module in net-snmp with python?
  • Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
  • sorl-thumbnail and file renaming
  • Python -- what is NOT in 2.7 that IS in 3.1? So many things have been back-ported, what is NOT?
  • How to make a Django model fields calculated at runtime?
  • Django - Threading in views without hanging the server
  • Python: Why is my POST requests not working?
  • Tried to add a value to a while condition, but it doesn't go back
  • How do I exit a while-true loop after 5 tries?
  • win python3 Multithreading
  • Compare 2 dictionaries in python
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk