Python SSH Session with User/Password Login - python-3.x

for my work i want to connect to serveral routers and configure them over SSH.
I try to do something in Python.
On Google i found serveral Tutorials for Paramiko or something else but i am not able to connect to the devices.
The routers are not in my Hand and the only to connect is username/password login.
Manual login over PuTTy works fine. But on unknown reasons the scripted login with Paramiko or PLINK.exe (with username and password parameter) is it not working.
Python Example for SSH Session:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
if ssh.get_transport() is not None:
print("Connected")
else:
print("Not Connected")
With this simple Snippet following Error is shown:
Error:
paramiko.ssh_exception.AuthenticationException: Authentication failed.
It looks like the password is not used.
I am wondering if there any way to establish an SSH connection with Python where the password send delayed via stdin?
Thx in advance,
Marcus

Related

Let subprocess.check_output timeout when there is a user prompt

I have python script that use scp to transfer some files to other remote hosts.
try:
out = subprocess.check_output(f"scp filename.txt user1#host1:/home/user1/", stderr=subprocess.STDOUT, timeout=15)
print(out)
except subprocess.TimeoutExpired as e:
print(e.output)
// Handle hostkey verification error
Now some times, its possible that the remote server isnt authenticated and part of known hosts files, in which case the script just forever stays in waiting state for user input with Are you sure you want to continue connecting (yes/no/[fingerprint])?
What i want is to be able to catch this scenario, so i can handle host key verification.
I tried adding timeout and catch the exception but instead of timing out it still stays in user prompt state.

How do i fix HTTPSConnectionPool - Read Timed Out Error when connecting to database server

I am trying to connect to a FileMaker Databse server via python script, and my code was working before but has suddenly stopped, and i didnt make any changes to the portion of code that no longer works. I am encountering the following error:
Request error: HTTPSConnectionPool(host='**.**.*.*', port=443): Read timed out. (read timeout=30)
I have taken out the code that creates the server instance and connects/logs in, and then logs out without making any changes in the database, and i am still recieving the same error. However, i can connect to the filemaker server and database via the FileMaker applicaiton with no issues, and i can connect to the server using Telnet commands. I am on windows 10 and writing the code in PyCharm CE. I have reinstalled PyCharm, created a new virtual environment, and tried reinstalling the fmrest module, as well as using older versions. I have also increased the timeout time to give more time to login, which hasnt worked. I'm basically stumped on why i can no longer log in via the script, when it has been working perfectly in testing for the past couple weeks. My code is below.
import fmrest
from fmrest.exceptions import FileMakerError
from fmrest.exceptions import RequestException
import sys
import requests
# connect to the FileMaker Server
requests.packages.urllib3.disable_warnings()
fmrest.utils.TIMEOUT = 30
try:
fms = fmrest.Server('https://**.**.*.*',
user = '***',
password = '******',
database = 'Hangtag Order Management',
layout = 'OrderAdmin',
verify_ssl = False)
except ValueError as err:
print('Failed to connect to server. Please check server credentials and status and try again\n\n' + str(err))
sys.exit()
print(fms)
print('Attempting to connect to FileMaker Server...')
try:
fms.login()
print('Login Successful\n')
except FileMakerError as err:
print(err)
sys.exit()
except RequestException as err:
print('There was an error connecting to the server, the request timed out\n\n' + str(err))
sys.exit()
fms.logout()
This should successfully login to the database, print 'login successful' and log out. Calling print(fms) returns
<Server logged_in=False database=Hangtag Order Management layout=OrderAdmin>
but i receive the connection error upon the login attempt. I am assuming the error is server side, but i dont know enough about servers to accurately trouble shoot. Could the server have blacklisted my IP for making so many login attempts during my testing? and if so where would i undo that/prevent it from happening again?
A couple of server reboots fixed the error, not really sure of the ultimate cause.

How to type the credentials manually in Parallel-SSH or Paramiko

I am trying to create a script that will run commands over my 1000 Cisco devices.
The device model is: Cisco Sx220 Series Switch Software, Version 1.1.4.1
The issue is that there is some kind of strange behavior for some of those Cisco devices.
When I am trying to login with regular SSH (PUTTY) with the correct credentials we are first getting 'Authentication Failure' and after 1 seconds I am getting the User Password Prompt again, typing the same credentials again is giving me a successful login.
The problem is that when I am trying to connect using my script (uses ParallelSSHClient), the connection drops after getting the authentication failure message and not able to enter the credentials again since it is getting the exception and terminal the program.
I am looking for a way to enter those credentials manual by connecting to the machine, getting the Authentication Failure message and ignoring it, recognizing that the current prompt has the User or Password appears on screen and then send it manually.
I look for this kind of procedure anywhere but without any luck.
Does ParallelSSHClient has this feature?
If Paramiko has it, I am willing to move to Paramiko.
Thanks :)
try:
client = ParallelSSHClient(hosts=ip_list, user=user, password=password)
except Exception as err:
print("There was an issue with connecting to the machine")
command_output = client.run_command(command)
Here is the accrual error that I am getting:
pssh.exceptions.AuthenticationException: ('Authentication error while connecting to %s:%s - %s', '172.31.255.10', 22, AuthenticationException('Password authentication failed',))

subprocess.Popen ssh tunnel launches 2nd process which requires answering a prompt with a pin

I am creating an ssh tunnel using subprocess.Popen. However to successfully create this tunnel I am using a Yubikey which requires a pin to release the keys for successful authentication, built in with ssh config. Code below is as far as I can get.
def launch_tunnel(self):
try:
enterpin = getpass.getpass()
bytepin = str.encode(enterpin)
launchtunnel = subprocess.Popen('ssh tunnel command',
shell=True,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
stderr=subprocess.PIPE).communicate(input=bytepin)
except Exception as e:
print(e)
When I run it I get the following 2 prompts.
Password:
Enter PIN for 'PIV_II (PIV Card Holder pin)':
First one being getpass.getpass() and the second one being another process which requires the Yubikey Pin. It's clear that .communicate() is not working here and from what I can tell it's because the ssh process spawns another process(the pin prompt) that requires the pin for ssh authentication.
Is there anyway to set the pin prior using something like getpass and pass it directly to the 2nd process. Currently this 2nd process(pin prompt) is interrupting the rest of my application so I would like to control it?
I found part of the solution. Using communicate() without anything in () halts the process at the prompt so I do not need to implement getpass before launching subprocess. It has given me another issue but I will take that to a new thread.
launchtunnel = subprocess.Popen(checktunnelexists[1], shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
launchtunnel.communicate()[0]

How can connect from one computer to another computer using python

I wanted to connect from one computer to another computer using python, (or remote computer)
I have installed wmi module and trying to use below code for connection from one computer to another computer,
ip = '100.00.00.00'
username = 'MyuserName'
password = 'myPassword'
#import sys, wmi
from socket import *
try:
print("Trying to connect %s" %ip)
wmi.WMI(ip, user=username,password = password)
print('connected')
except wmi.x_wmi:
print("Wrong username or password"
While running above code, I am getting error - except wmi.x_wmi:
NameError: name 'wmi' is not defined
Could you please help me for connecting from one computer to another computer
Thanks in advance
RaviK
It looks like your fourth line:
#import sys, wmi
probably just needs to be uncommented
import sys, wmi
If you still get the error you might need to install the wmi library

Resources