Paramiko Emulating IBM 3151. How do I send the right control keypress - python

I am using Python 2.7 Paramiko to SSH into a very old system that uses IBM 3151 keymapping. Keyboards back then had an enter or "send" key used to submit responses. In Secure NetTerm, I am able to access this system and the "send" key is mapped to the right ctrl key on the keyboard. For the life of me, I can't figure out how to send the "send" key to the terminal with Paramiko. Below is my test code. I am able to make it through the first few menu options which accept \n, but I am running into a "popup" screen that requires the "send" key. Pressing the right ctrl key works in the emulator, but I can't seem to get anything to work in Paramiko. Any help would be appreciated.
import paramiko
import time
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect('some_server.com', port=22,username='some_user', password='some_password')
except paramiko.SSHException:
print "Connection Failed"
quit()
channel = ssh.invoke_shell(term='IBM-3151', width=80, height=24, width_pixels=0, height_pixels=0)
channel_data = str()
host = str()
srcfile = str()
while True:
if channel.recv_ready():
channel_data += channel.recv(9999)
else:
continue
print channel_data
#Go to store
if channel_data.endswith('> '):# in channel_data:
channel.send('5\n')
# Select a store
if channel_data.endswith(' : '): # in channel_data:
channel.send('0330\n')
if channel_data.endswith('): '): # in channel_data:
channel.send('Y\n')
if 'PRESS SEND TO CONTINUE....' in str(channel_data):
print 'test1' # if statement works
time.sleep(5)
channel.send('^[!l^M') # tried all kinds of stuff here
print 'test2' # script passes to here with no errors.

I'd determine what characters are actually sent by the Send (or Enter) key by
capture all of the characters from a session using script on the AIX system (you might need this for analysis)
in a shell on the AIX system, use cat (to echo) and press control-V before pressing *Enter.
Do that with the working terminal of course. If the data shown by cat does not work with your script, it's possible that there's some initialization done, e.g., putting Secure NetTerm into application mode.

Related

Trying to integrate paramiko and pyTelegramBotAPI

I am new at programming using python. I am trying to create a python script that connects to different Linux servers to extract data or check if some services are running. I am able to send a command -> use paramiko to extract data -> send the data to telegram. The problem is that i am trying to make the code shorter creating a file only for functions and call it but i can not get this to work. Here is the file(no executable) and the code:
File:
def tx(message):
host = "111.222.333.444"
user = "user"
password = "12345"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=user, password=password)
stdin, stdout, stderr = ssh.exec_command("sudo tail -1 /usr/local/bin/noc/respaldos/diatx.txt")
time.sleep(.5)
output = stdout.readlines()
ssh.close()
return output
Script:
import telebot
import paramiko
import time
import commands
TOKEN = "abcde"
bot = telebot.TeleBot(TOKEN)
#bot.message_handler(commands=['tx'])
commands.tx(message)
bot.send_message(message.chat.id, output)
bot.polling()
My intention is to create 20 functions for different data and checks but all in functions inside the commands.py file. I have tried with from commands import * but that did not work either
I see a few problems in your code.
First, I don't see message being defined anywhere.
Second, the way you use the bot.message_handler decorator.
The decorator function returns a function object that will replace the function you decorate. See the code:
#bot.message_handler(commands=['tx'])
def tx(message):
command.tx(message)
However, I don't know telebot library. I'm not sure how this is supposed to work.

Can not connect via AsyncSSH, error Host key is not trusted

When I run this script I receive SSH connection failed: Host key is not trusted error, but even connect to this host to take the key, keep to receive this error.
import asyncio, asyncssh, sys
async def run_client():
async with asyncssh.connect('172.18.17.9', username="user", password="admin", port=9321) as conn:
result = await conn.run('display version', check=True)
print(result.stdout, end='')
try:
asyncio.get_event_loop().run_until_complete(run_client())
except (OSError, asyncssh.Error) as exc:
sys.exit('SSH connection failed: ' + str(exc))
Try adding the known_hosts=None parameter to the connect method.
asyncssh.connect('172.18.17.9', username="user", password="admin", port=9321, known_hosts=None)
From asyncssh documentation here:
https://asyncssh.readthedocs.io/en/latest/api.html#asyncssh.SSHClientConnectionOptions
known_hosts (see Specifying known hosts) – (optional) The list of keys
which will be used to validate the server host key presented during
the SSH handshake. If this is not specified, the keys will be looked
up in the file .ssh/known_hosts. If this is explicitly set to None,
server host key validation will be disabled.
With me, it runs smoothly after inserting known_hosts=None
Here's my example when trying the coding sample in Ortega book:
I tried with hostname=ip/username/password of localCentOS, command test is ifconfig
import asyncssh
import asyncio
import getpass
async def execute_command(hostname, command, username, password):
async with asyncssh.connect(hostname, username = username,password=password,known_hosts=None) as connection:
result = await connection.run(command)
return result.stdout
You should always validate the server's public key.
Depending on your use case you can:
Get the servers host keys, bundle them with your app and explicitly pass them to asyncssh (e.g., as string with a path to your known_hosts file).
Manually connect to the server on the command line. SSH will then ask you if you want to trust the server. The keys are then added to ~/.ssh/known_hosts and AsyncSSH will use them.
This is related but maybe not totally your salvation:
https://github.com/ronf/asyncssh/issues/132
The real question you should be asking yourself as you ask this question (help us help you) is where is it all failing? Known-hosts via analogy is like env vars that don't show up when you need them to.
EDIT: Questions that immediately fire. Host key is found but not trusted? Hmm?
EDIT2: Not trying to be harsh towards you but I think it's a helpful corrective. You've got a software library that can find the key but is not known. You're going to come across a lot of scenarios with SSH / shell / env var stuff where things you take for granted aren't known. Think clearly to help yourself and to ask the question better.

Python PhantomJS Sending Keys to Text Field Not Working

So I'm having a weird problem with PhantomJS where it is continually failing to send text to the text input field. When I run my code with a chrome driver, there is no issue, and everything works as expected.
This is the chat box on twitch streams if you were wondering. Here is some code.
print("Finding chat box...")
typeKeyword = wait_until_visible_by_xpath('//textarea[#placeholder="Send a message"]', browser)
not_working = True
while not_working:
try:
print("Sending keys...")
typeKeyword.send_keys("hi")
not_working = False
except InvalidElementStateException:
sleep(3)
print("Hitting chat button")
chatButton = wait_until_visible_by_xpath('//button[#class="button send-chat-button primary float-right"]', browser)
chatButton.click()
PhantomJS is able to locate the text field, but it keeps getting trapped on the InvalidElementStateException when it is checking whether it can send the keys or not. There should be a small delay because the twitch chat box is usually grayed out for 6-10 seconds before it becomes able to type in it. With the chrome driver, after printing "Sending keys..." about 3 times, the code finishes up and the message is typed. With PhantomJS, however, it prints "Sending keys..." forever.
Refind/"refresh" the element inside the loop:
while not_working:
typeKeyword = browser.find_element_by_xpath('//textarea[#placeholder="Send a message"]')
...

(Python impacket) smb Server with Logon?

I'm trying to implement an authentication section into the smbserver.py from the impacket lib.
I changed the errorCode at the Line 2201 to STATUS_LOGON_FAILURE under some conditions, but my windows client keeps requesting with the same credentials like 10 times before he asks the user to enter new credentials. When I submit the windows dialog the credentials dont get sent to the script.
Heres my code section:
if not authenticateMessage['user_name'] == "testUser":
print "username not valid"
errorCode = STATUS_LOGON_FAILURE
respToken['NegResult'] = '\x02'
else:
print "logged in" + authenticateMessage['user_name']
errorCode = STATUS_SUCCESS
respToken['NegResult'] = '\x00'
Did somebody write a working authentication section there? Thanks!
The link you have provided is not the official repository for the library. Use https://github.com/CoreSecurity/impacket in the future.
The code you specified is almost right except the fact that the user_name field inside the authenticateMessage is Unicode encoded.
You can see the contents of the authenticateMessage structure by calling its dump() method (authenticateMessage.dump()).
I've replaced your code with:
authenticateMessage.dump()
respToken = SPNEGO_NegTokenResp()
if authenticateMessage['user_name'].decode('utf-16le') == "testUser":
errorCode = STATUS_SUCCESS
respToken['NegResult'] = '\x00'
else:
errorCode = STATUS_LOGON_FAILURE
respToken['NegResult'] = '\x02'
If you cloned master (https://github.com/CoreSecurity/impacket) you will see a new example called examples/smbserver.py (don't get confused with the impacket/smbserver.py library) which makes it easier to launch a simple server. Just run:
smbserver.py shareName sharePath
(e.g. smbserver.py TMP /tmp)
I made the aforementioned changes and ran the smbserver.py example and then, from a windows 7 cmd.exe prompt I ran (assuming the SMB server runs at 172.16.123.1 and the logged in username is not testUser):
start \\172.16.123.1
If you sniff the traffic you will see three attempts to login unsuccessfully and then Windows Explorer will popup a dialog box asking for new credentials. If you specify testUser as username (password can be anything) you will end up connecting to the target SMB server.

Checking if website responds in python using a browser user agent

I am trying to come up with a script to check if a domain name resolves to its IP address via dns; using a python script I wrote.
I want to be able to do this in a few sequential loops, however after trying to run a loop once, the second time i run the script, the names that previously returned a successful dns resolution response, now do not.
Below is my script:
#! C:\Python27
import socket,time
localtime = time.asctime( time.localtime(time.time()) )
def hostres(hostname):
print "Attempting to resolve " + hostname
try:
socket.gethostbyname(hostname)
print "Resolved Successfully!"
except socket.error:
print "Could Not Resolve"
print "*************************************************"
print "Website loop starting.."
print "Local current time :", localtime
print "*************************************************"
print ""
text_file = open("sites.txt", "r")
lines = text_file.readlines()
for line in lines:
hostres(line)
text_file.close()
The contents of the text file are:
www.google.com
en.wikipedia.org
www.youtube.com
us.gamespot.com
I am thinking it is to do with these domains servers recognizing the script as a "bot" rather than a legitimate end-user, would it be correct to assume this?
If so, how can I still check if the dns name resolves by looking up the name of the website (or IP, does not matter) and be able to run this without getting a false reading of "request failed" despite the fact that the service is fully accessible from a browser?
Several problems in this question.
You are not checking if "a website responds" you are testing DNS resolution. All your DNS requests go to a single name server, your LDNS resolver. If all of them resolve, it still says nothing about the status of the website. Also, since you aren't actually talking to these website, they have no way of knowing you're a bot. They can only detect this (based on the HTTP user-agent header) if you make a HTTP request.
Regarding your code problem, you need to trim the newline character before you can do a socket.gethostbyname() on it. Replace socket.gethostbyname(hostname) with socket.gethostbyname(hostname.rstrip()) and you'll be fine.

Categories