How to type the credentials manually in Parallel-SSH or Paramiko - python-3.x

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',))

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.

Python SSH Session with User/Password Login

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

How to control UserID in pymqi?

Got a trouble:
IBM MQ Server v9.1.0.0
pymqi==1.11.1
When trying connect to server got an error:
pymqi.MQMIError: MQI Error. Comp: 2, Reason 2035: FAILED: MQRC_NOT_AUTHORIZED
When I check traffic in Wireshark i got that:
And in server log this:
07/31/2020 10:08:02 AM - Process(27333.5) User(mqm) Program(amqrmppa)
Host(host) Installation(Installation1)
VRMF(9.1.0.0) QMgr(queue_manager)
Time(2020-07-31T07:08:02.253Z)
ArithInsert1(2) ArithInsert2(2035)
CommentInsert1(haha)
AMQ9557E: Queue Manager User ID initialization failed for 'haha'.
EXPLANATION:
The call to initialize the User ID 'haha' failed with CompCode 2 and Reason
2035. If an MQCSP block was used, the User ID in the MQCSP block was ''.
ACTION:
Correct the error and try again.
My code sample:
import pymqi
host = "host"
port = 1416
conn_info = f"{host}({port})"
channel = "channel"
queue_manager = "queue_manager"
def main():
manager = pymqi.connect(queue_manager=queue_manager, channel=channel, conn_info=conn_info)
if __name__ == '__main__':
main()
I tried to execute the code from other devices and there, accordingly, the account under which I ran was taken as the UserID.
After that I asked our support to deal with the problem, after which I was able to connect with an account haha, but the solution with the creation of a list of allowed users does not suit me. Is there any way to control the UserID that is sent by pymqi?
UPD 04.08.2020
The support team said that the user phoenix was created on the IBM MQ server with the password 123456789, tried to send an MQSCP:
manager = pymqi.connect(queue_manager=queue_manager, channel=channel,
conn_info=conn_info, user="phoenix", password="123456789")
And got similar error MQRC_NOT_AUTHORIZED and server log contains error as above with username of machine where code launches (not phoenix).

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.

Steam 2FA throwing "Failed to get a web session" consistantly

I'm using steam's python library to create an app for generating 2FA codes. The issue is that steam throws me this error whenever I try to add a phone number or add 2FA to said account:
RuntimeError: Failed to get a web session. Try again in a few minutes
Fri Mar 30 08:39:04 2018 <Greenlet at 0x6e64580: handle_after_logon> failed with RuntimeError
Yes I've waited a few minutes and have been trying for hours.
Here's the code that I'm using to attempt this:
from steam import SteamClient
from steam.enums.emsg import EMsg
from steam.guard import SteamAuthenticator
#Create our steamclient instance
client = SteamClient()
#client.on("logged_on")
def handle_after_logon():
print("You are now Logged in.")
#Setup Autenticator for our steamclient instance "client". "client" is our logged in SteamClient instance as requested by documentation
sa = SteamAuthenticator(medium=client)
#My account has no phone number
print(sa.has_phone_number())
#Adding phone number because I know ahead of time I don't have it
sa.add_phone_number("myphonenumber with area code")
sa.add() # SMS code will be sent to account's phone number
sa.secrets # dict with authenticator secrets
#We're gonna need these
print(sa.secrets)
sa.finalize(str(input("SMS CODE: "))) # activate the authenticator
sa.get_code() # generate 2FA code for login
sa.remove() # removes the authenticator from the account
try:
#Login to our steamclient instance
client.cli_login("myusername","mypassword")
#client.on("loggon_on") doesn't trigger without this
client.run_forever()
#Allow us to logout using keyboard interrupt
except KeyboardInterrupt:
if client.connected:
client.logout()
Due to a lack of example code on 2FA in particular I've followed the documentation the best I could, I've looked at all of the below:
http://steam.readthedocs.io/en/latest/api/steam.client.html
http://steam.readthedocs.io/en/latest/api/steam.guard.html
https://github.com/ValvePython/steam/blob/master/recipes/1.Login/persistent_login.py
I feel like there's simply a silly error in my code, but reading through the documentation doesn't appear to be helping me solve this.
Thanks for your guys help.
I debugged for a while and it's an issue with gevent
I added this line to fix it at the beginning of my script:
from gevent import monkey
monkey.patch_all(thread=False)

Resources