logo
down
shadow

Using ready paramiko connection


Using ready paramiko connection

By : user2952551
Date : November 19 2020, 01:01 AM
this one helps. Here is an example for you. It can work as a ssh client. No need to recreate session everytime.
code :
#!/usr/bin/env python
#-*- coding:utf-8 -*-


import os,sys  
import paramiko    
import threading    
import platform  

curr_ssh = None   
curr_prompt = ">>"  

#how to use it    
def printUsage():  
    print "    !ls                     :list sessions."  
    print "    !session id             :connect session."  
    print "    !conn host user password:connect host with user."  
    print "    !exit                   :exit."  

#connect using paramiko   
def conn(ip,username,passwd):  
    try:  
        ssh = paramiko.SSHClient()    
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    
        ssh.connect(ip,22,username,passwd,timeout=5)    
        print "Connect to ",ip," with ",username  
        global curr_prompt  
        curr_prompt=username+"@"+ip+">>"  
        return ssh  
    except:  
        return None  

#get former session
sessions=[]  
def loadSessions():  
    global sessions  
    try:  
        f = open("sessions")  
        sessions = f.readlines()  
        f.close()  
    except:  
        pass  

#main function   
def exe_cmd_local(cmd):  
    if(cmd == "!ls"):  
        loadSessions()  
        global sessions  
        i=0  
        print "Sessions:"  
        for s in sessions:  
            print"[%d] %s" %(i,s)  
            i+=1  
    else:  
        vals = cmd.split(' ')  
        if(vals[0]=="!session"):  
            id = (int)(vals[1])  
            if(id<len(sessions)):  
                os_name = platform.system()  

                new_console_cmd = ""  
                if(os_name == "Linux"):  
                    new_console_cmd="gnome-terminal -e \"./ssh.py " + sessions[id]+"\""  
                elif(os_name == "Windows"):  
                    new_console_cmd="start ssh.py " + sessions[id]  
                os.system(new_console_cmd)  
            else:  
                print "Didn't hava sessoin ",vals[1]  
        elif(vals[0]=="!conn"):  
            global curr_ssh  
            curr_ssh = conn(vals[1],vals[2],vals[3])  
            f = open("sessions","a")  
            line = vals[1]+" "+vals[2]+" "+vals[3]+"\n"  
            f.write(line)  
            f.close()  

#execute command remotely    
def exe_cmd_ssh(ssh,cmd):  
    if(ssh == None):  
        print "Didn't connect to a server. Use '!conn' to connect please."  
        return  
    stdin, stdout, stderr = ssh.exec_command(cmd)    
    print stdout.read()  
    print stderr.read()  

if __name__=='__main__':  
    loadSessions()  
    if(len(sys.argv)==4):  
        curr_ssh = conn(sys.argv[1],sys.argv[2],sys.argv[3])  
    else:  
        printUsage()  
    while True:  
        cmd = raw_input(curr_prompt)  
        if(len(cmd)==0):  
            continue  

        if(cmd == "!exit"):  
            if(curr_ssh != None):  
                curr_ssh.close();  
            break  
        else:  
            if(cmd[0] == '!'):  
                exe_cmd_local(cmd)  
            else:  
                exe_cmd_ssh(curr_ssh,cmd)  


Share : facebook icon twitter icon
Paramiko connection issue

Paramiko connection issue


By : user2653508
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I tried the code and it ran fine. I made only a few changes.
First, I didn't know what "user" and "db" are, so I commented out
code :
import user, db
database = db.Database()
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()
How to add host_key temporarily in a paramiko connection

How to add host_key temporarily in a paramiko connection


By : user3604006
Date : March 29 2020, 07:55 AM
To fix the issue you can do I'm connecting to a SSH server using Paramiko, and I want to add the "host_keys" temporarily.
paramiko allows sftp connection without key

paramiko allows sftp connection without key


By : Mike Gustus
Date : March 29 2020, 07:55 AM
help you fix your problem It looks like this is an acceptable practice.
Comment from Transport.connect
Max value of Paramiko SSH connection timeout?

Max value of Paramiko SSH connection timeout?


By : ASHA PATIL
Date : March 29 2020, 07:55 AM
I hope this helps you . I think you have to set it at kernel level. Paramiko set the timeout via socket.settimeout(), and this through the OS (I'm not sure of this, but your case seems so). Linux have its timeout set to 20 seconds (read this). In that same link, they explain how to increase the socket timeout:
Related Posts Related Posts :
  • Remove commas in a string, surrounded by a comma and double quotes / Python
  • How to chain Django querysets preserving individual order
  • Comparison with Python
  • How to find backlinks in a website with python
  • Return new instance of subclass when using methods inherited from parent class in Python
  • Which function in django.contrib.auth creates the default model permissions?
  • Formatting text in tabular form with Python
  • How to determine the first day of a month in Python
  • Error while converting date to timestamp in python
  • Python string iterations
  • Is there any file number limitation when you select multiple files with wxFileDialog?
  • Errors with Matplotlib when making an executable with Py2exe (Python)
  • Django Haystack - Indexing single field
  • Go Pro Hero 3 - Streaming video over wifi
  • Appending a column in .csv with Python/Pandas
  • How to change my result directory in Robot framework using RIDE?
  • problem with using pandas to manipulate a big text file in python
  • python-magic module' object has no attribute 'open'
  • Where goes wrong for this High Pass Filter in Python?
  • Why inserting keys in order into a python dict is faster than doint it unordered
  • flann index saving in python
  • Create new instance of list or dictionary without class
  • How can I easily convert FORTRAN code to Python code (real code, not wrappers)
  • Address of lambda function in python
  • Python adding space between characters in string. Most efficient way
  • python http server, multiple simultaneous requests
  • Disguising username & password on distributed python scripts
  • Post GraphQL mutation with Python Requests
  • Why doesnt pandas create an excel file?
  • Rolling comparison between a value and a past window, with percentile/quantile
  • How to avoid repetitive code when defining a new type in python with signature verification
  • How to configure uWSGI in order to debug with pdb (--honour-stdin configuration issue)
  • In Python, how do you execute objects that are functions from a list?
  • Python- Variable Won't Subtract?
  • Processing Power In Python
  • Python 2.7.2 - Cannot import name _random or random from sys
  • Why doesn't the Python sorted function take keyword order instead of reverse?
  • Make a function redirect to other functions depending on a variable
  • get_absolute_url in django-categories
  • Monitoring non-Celery background task with New Relic in Python
  • Feature selection with LinearSVC
  • LSTM - Predicting the same constant values after a while
  • Test the length of elements in a list
  • Django: render radiobutton with 3 columns, cost column must change according to size & quantity selected
  • Python class attributes vs global variable
  • sys.stdout.writelines("hello") and sys.stdout.write("hello")
  • is ndarray faster than recarray access?
  • Python - search through directory trees, rename certain files
  • GAE: How to build a query where a string begins with a value
  • TypeError: __init__() takes at least 2 arguments (1 given)
  • Overriding and customizing "django.contrib.auth.views.login"
  • Django : Redirect to a particular page after login
  • Python search and copy files in directory
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org