pysnmp setcmd "No Such Object currently exists at this OID" - pysnmp

I need to set some OID parameters using Python.
I made this simple script using pysnmp library. It correctly reads OID's but when I try to set one just read I receive the message "No Such Object currently exists at this OID".
Can help me? Thank you in advance.
from pysnmp.hlapi import *
print "Get OID"
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
CommunityData('public'),
UdpTransportTarget((hostIP, 161)),
ContextData(),
ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')),
ObjectType(ObjectIdentity('1.3.6.1.2.1.1.6.0')),
ObjectType(ObjectIdentity('1.3.6.1.2.1.1.9.1.2.1')),
ObjectType(ObjectIdentity('1.3.6.1.2.1.1.9.1.3.1')))
)
for varBind in varBinds:
print varBind
print "Set OID"
errorIndication, errorStatus, errorIndex, varBinds = next(
setCmd(SnmpEngine(),
CommunityData('public', mpModel=0),
UdpTransportTarget((hostIP, 161)),
ContextData(),
ObjectType(ObjectIdentity('1.3.6.1.2.1.1.9.1.3.1'),
OctetString('new value')))
)
for varBind in varBinds:
print varBind
I used a MIB Browser (CommunityData='private' for setting) and I was able to set specific OID for that snmp v2 device (Selta ONU), providing credentials in specific OID's.
This was the sequence of setting:
1.3.6.1.4.1.10060.1.6.10.4.1.1.0 = "username"
1.3.6.1.4.1.10060.1.6.10.4.1.2.0 = "password"
1.3.6.1.4.1.10060.1.6.10.4.2.0=1 (session status = START)
after the session is started I set the parameter
1.3.6.1.4.1.10060.1.6.6.3.29.1.4.1 = "17a_RTX"
1.3.6.1.4.1.10060.1.6.10.4.2.0=3 (session status = COMMIT)
so the new value was stored.
After this successful experience I modified the Python script in this way:
from pysnmp.hlapi import *
print "Get OID"
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
CommunityData('public'),
UdpTransportTarget(('163.162.105.120', 161)),
ContextData(),
ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')),
ObjectType(ObjectIdentity('1.3.6.1.2.1.1.6.0')),
ObjectType(ObjectIdentity('1.3.6.1.4.1.10060.1.6.10.4.3.0')) # get session status
)
)
for varBind in varBinds:
print varBind
print "Set Credentials"
errorIndication, errorStatus, errorIndex, varBinds = next(
setCmd(SnmpEngine(),
CommunityData('private', mpModel=1),
UdpTransportTarget(('163.162.105.120', 161)),
ContextData(), ObjectType(ObjectIdentity('1.3.6.1.4.1.10060.1.6.10.4.1.1.0'),OctetString('username')),
ObjectType(ObjectIdentity('1.3.6.1.4.1.10060.1.6.10.4.1.2.0'),OctetString('password')),
ObjectType(ObjectIdentity('1.3.6.1.4.1.10060.1.6.10.4.2.0'),Integer(1)) # open session
)
)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for varBind in varBinds:
print varBind
print "Set OID"
errorIndication, errorStatus, errorIndex, varBinds = next(
setCmd(SnmpEngine(),
CommunityData('private', mpModel=1),
UdpTransportTarget(('163.162.105.120', 161)),
ContextData(), ObjectType(ObjectIdentity('1.3.6.1.4.1.10060.1.6.6.3.29.1.4.1'),OctetString('17a_noRTX')))
)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for varBind in varBinds:
print varBind
Unfortunately I got the following error:
Get OID
SNMPv2-MIB::sysDescr.0 = SAMBHA
SNMPv2-MIB::sysLocation.0 = Cadeo(PC)
SNMPv2-SMI::enterprises.10060.1.6.10.4.3.0 = 0
Set Credentials
'noSuchName' at 1.3.6.1.4.1.10060.1.6.10.4.1.2.0
Set OID
'authorizationError' at 1.3.6.1.4.1.10060.1.6.6.3.29.1.4.1
The same OID 1.3.6.1.4.1.10060.1.6.10.4.1.2.0 that was set in MIB Browser is not seen in the script.
Have you any suggestions?

I do not see any issues with your code so far. I am pretty confident that's your SNMP agent not allowing you to modify the managed object you want to modify.
Does it work with Net-SNMP's snmpset?
snmpset -v1 -c public 1.3.6.1.2.1.1.9.1.3.1 s 'new value'
BTW, often times SNMP agents are configured to use different SNMP community strings for read and write operations. Sometimes the default is private for writes.

#Ilya, my tries with net-snmp.
snmpget -v 2c -c public 163.162.105.120 1.3.6.1.4.1.10060.1.6.6.3.29.1.11.1
SNMPv2-SMI::enterprises.10060.1.6.6.3.29.1.11.1 = STRING: "VirtualNoiseProfile"
snmpset -v 2c -c public 163.162.105.120 1.3.6.1.4.1.10060.1.6.6.3.29.1.11.1 s "new string"
Error in packet.
Reason: noAccess
snmpset -v 2c -c private 163.162.105.120 1.3.6.1.4.1.10060.1.6.6.3.29.1.11.1 s "new string"
Error in packet.
Reason: authorizationError (access denied to that object)
Failed object: SNMPv2-SMI::enterprises.10060.1.6.6.3.29.1.11.1
The host doesn't allow set operation, nor public neither private, also if the python message is
misleading ("No Such Object currently exists at this OID").
I should learn how to set an authorization profile, I suppose. But I haven't found any examples.
Thank you.

Related

Save job output from SDSF into a PDS and using ISPF functions in REXX

We periodically runs jobs and we need to save the output into a PDS and then parse the output to extract parts of it to save into another member. It needs to be done by issuing a REXX command using the percent sign and the REXX member name as an SDSF command line. I've attempted to code a REXX to do this, but it is getting an error when trying to invoke an ISPF service, saying the ISPF environment has not been established. But, this is SDSF running under ISPF.
My code has this in it (copied from several sources and modified):
parse arg PSDSFPARMS "(" PUSERPARMS
parse var PSDSFPARMS PCURRPNL PPRIMPNL PROWTOKEN PPRIMCMD .
PRIMCMD=x2c(PPRIMCMD)
RC = isfquery()
if RC <> 0 then
do
Say "** SDSF environment does not exist, exec ending."
exit 20
end
RC = isfcalls("ON")
Address SDSF "ISFGET" PPRIMPNL "TOKEN('"PROWTOKEN"')" ,
" (" VERBOSE ")"
LRC = RC
if LRC > 0 then
call msgrtn "ISFGET"
if LRC <> 0 then
Exit 20
JOBNAME = value(JNAME.1)
JOBNBR = value(JOBID.1)
SMPDSN = "SMPE.*.OUTPUT.LISTINGS"
LISTC. = ''
SMPODSNS. = ''
SMPODSNS.0 = 0
$ = outtrap('LISTC.')
MSGVAL = msg('ON')
address TSO "LISTC LVL('"SMPDSN"') ALL"
MSGVAL = msg(MSGVAL)
$ = outtrap('OFF')
do LISTCi = 1 to LISTC.0
if word(LISTC.LISTCi,1) = 'NONVSAM' then
do
parse var LISTC.LISTCi . . DSN
SMPODSNS.0 = SMPODSNS.0 + 1
i = SMPODSNS.0
SMPODSNS.i = DSN
end
IX = pos('ENTRY',LISTC.LISTCi)
if IX <> 0 then
do
IX = pos('NOT FOUND',LISTC.LISTCi,IX + 8)
if IX <> 0 then
do
address ISPEXEC "SETMSG MSG(IPLL403E)"
EXITRC = 16
leave
end
end
end
LISTC. = ''
if EXITRC = 16 then
exit 0
address ISPEXEC "TBCREATE SMPDSNS NOWRITE" ,
"NAMES(TSEL TSMPDSN)"
I execute this code by typing %SMPSAVE next to the spool output line on the "H" SDSF panel and it runs fine until it gets to this point in the REXX:
114 *-* address ISPEXEC "TBCREATE SMPDSNS NOWRITE" ,
"NAMES(TSEL TSMPDSN)"
>>> "TBCREATE SMPDSNS NOWRITE NAMES(TSEL TSMPDSN)"
ISPS118S SERVICE NOT INVOKED. A VALID ISPF ENVIRONMENT DOES NOT EXIST.
+++ RC(20) +++
Does anyone know why it says I don't have a valid ISPF environment and how I can get around this?
I've done quite a bit in the past with REXX, including writing REXX code to handle line commands, but this is the first time I've tried to use ISPEXEC commands within this code.
Thank you,
Alan

How do i make a registration form whic stores useres data in .txt file in python?

I am working on a project which I am spouse to create a Bank system using python. I have done the program and it works perfectly the only problem that I need help with is that how to create a registration form which will store user data for sign up, and read data for login from a txt file.
=
balance = 100
def log_in():
tries = 1
allowed = 5
value = True
while tries < 5:
print('')
pin = input('Please Enter You 4 Digit Pin: ')
if pin == '1234':
print('')
print(" Your Pin have been accepted! ")
print('---------------------------------------------------')
print('')
return True
if not len(pin) > 0:
tries += 1
print('Username cant be blank, you have,',(allowed - tries),'attempts left')
print('')
print('---------------------------------------------------')
print('')
else:
tries += 1
print('Invalid pin, you have',(allowed - tries),'attempts left')
print('')
print('---------------------------------------------------')
print('')
print("To many incorrect tries. Could not log in")
ThankYou()
def menu():
print (" Welcome to the Python Bank System")
print (" ")
print ("Your Transaction Options Are:")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("1) Deposit Money")
print ("2) Withdraw Money")
print ("3) Check Balance")
print ("4) Quit Python Bank System.pyw")
def option1():
print (' Deposit Money' )
print('')
print("Your balance is £ ",balance)
Deposit=float(input("Please enter the deposit amount £ "))
if Deposit>0:
forewardbalance=(balance+Deposit)
print("You've successfully deposited £", Deposit, "into your account.")
print('Your avalible balance is £',forewardbalance)
print('')
print('---------------------------------------------------')
service()
else:
print("No deposit was made")
print('')
print('---------------------------------------------------')
service()
def option2():
print (' Withdraw Money' )
print('')
print("Your balance is £ ",balance)
Withdraw=float(input("Enter the amount you would like to Withdraw £ "))
if Withdraw>0:
forewardbalance=(balance-Withdraw)
print("You've successfully withdrawed £",Withdraw)
print('Your avalible balance is £',forewardbalance)
if Withdraw >= -100:
print("yOU ARE ON OVER YOUR LIMITS !")
else:
print("None withdraw made")
def option3():
print("Your balance is £ ",balance)
service()
def option4():
ThankYou()
def steps():
Option = int(input("Enter your option: "))
print('')
print('---------------------------------------------------')
if Option==1:
option1()
if Option==2:
option2()
if Option==3:
option3()
if Option==4:
option4()
else:
print('Please enter your option 1,2,3 or 4')
steps()
def service():
answer = input('Would you like to go to the menu? ')
answercov = answer.lower()
if answercov == 'yes' or answercov == 'y':
menu()
steps()
else:
ThankYou()
def ThankYou():
print('Thank you for using Python Bank System v 1.0')
quit()
log_in()
menu()
steps()
I expect my program to have a registration form which will store user data for sign up and read data for login from a .txt file.
So I looked a bit on it, and tried to do it with a .txt file.
So, in the same folder as the .py file, create the data.txt file like this one:
1234 1000.0
5642 500
3256 50.0
6543 25
2356 47.5
1235 495
1234 600000
The PIN and the balance are separated by a tabulation.
Then in the code, first step is to use global variable to pass on both the PIN number, the balance, and the path to the data file. Then, the data file is open, and the balance and pin are placed into 2 lists.
If you want to work with a dataframe, for instance panda, a dictionnary structure would be more relevant.
# Create the global variable balance and pin that will be used by the function
global balance
global pin
# Path to the data.txt file, here in the same folder as the bank.py file.
global data_path
data_path = 'data.txt'
data = open("{}".format(data_path), "r")
# Create a list of the pin, and balance in the data file.
pin_list = list()
balance_list = list()
for line in data.readlines():
try:
val = line.strip('\t').strip('\n').split()
pin_list.append(val[0])
balance_list.append(val[1])
except:
pass
# Close the data file
data.close()
""" Output
pin_list = ['1234', '5642', '3256', '6543', '2356', '1235', '1234']
balance_list = ['1000', '500', '-20', '25', '47.5', '495', '600000']
"""
Then, every function modifying the balance need to change the global variable value. For instance:
def log_in():
global balance
global pin
tries = 1
allowed = 5
while tries < 5:
pin = input('\nPlease Enter You 4 Digit Pin: ')
if pin in pin_list:
print('\n Your Pin have been accepted! ')
print('---------------------------------------------------\n')
balance = float(balance_list[pin_list.index(pin)])
menu()
else:
tries += 1
print('Wrong PIN, you have {} attempts left.\n'.format(allowed - tries))
print('---------------------------------------------------\n')
print('To many incorrect tries. Could not log in.')
ThankYou()
Or:
def option1():
global balance
print (' Deposit Money\n')
print('Your balance is £ {}'.format(balance))
deposit = float(input('Please enter the deposit amount £ '))
if deposit > 0:
balance = balance + deposit
print("You've successfully deposited £ {} into your account.".format(deposit))
print('Your avalible balance is £ {}\n'.format(balance))
print('---------------------------------------------------')
service()
else:
print('No deposit was made. \n')
print('---------------------------------------------------')
service()
Others sources of improvement:
Instead of print ('') to skip a line, simply add '\n' to the printed string.
Use 'blabla {}...'.format(value to put in {}) to place values, or str, or whatever in the middle of a str. It's good to use it since you will be able to place multiple values in the same string. Illustration in the saving data part bellow.
Finally, the new balance must be save in the .txt file. This will be done in the Thank you function:
def ThankYou():
global balance
global pin
global data_path
balance_list[pin_list.index(pin)] = balance
data = open("{}".format(data_path), "w")
for i in range(len(pin_list)):
line = '{}\t{}\n'.format(str(pin_list[i]), str(balance_list[i]))
data.write(line)
data.close()
print('Thank you for using Python Bank System v 1.0')
quit()
I hope you get the idea, and can manage on your own the code modifications, you should have every key to do it.
Good luck !

How can I take my captured information from a network/port scan and write that to a file?

I wrote an IP and port scanning program and I want to take the captured data and output it to a text file. I've been trying to figure it out for a while and haven't had any luck applying what I can find in searches. At the end, I commented out how I thought it should work to write the information to a file.
Any help or suggestions would be greatly appreciated, I'm still somewhat new to Python and trying to learn.
#!/usr/bin/env python
import ipaddress
import sys, time
import os
import subprocess
import socket
from datetime import datetime
FNULL = open(os.devnull, 'w')
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print ('Welcome to the IP/Port Scanner and Logger')
address = input('Enter starting IP address: ')
split1 = first,second,third,fourth = str(address).split('.')
start = int(fourth)
host = first+'.'+second+'.'+third+'.'+str(start)
end_address = input('Enter the ending IP address: ')
split2 = first,second,third,fourth = str(end_address).split('.')
end = int(fourth)
network = first+'.'+second+'.'+third+'.'
min_port = input("Enter starting port range: ")
max_port = input("Enter ending port range: ")
remoteserver = host
remoteserverIP = socket.gethostbyname(remoteserver)
def port_scan():
print ('Port scanning function initialized:')
try:
for port in range(int(min_port),int(max_port)):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteserverIP, port))
if result == 0:
print ('Port ' + str(port) + ': Open')
sock.close()
except KeyboardInterrupt:
print ("You halted the process")
sys.exit()
except socket.gaierror:
print ('Hostname could not be resolved. Exiting')
sys.exit()
except socket.error:
print ("Couldn't connect to server")
sys.exit()
return port
def check_up():
for ip_address in range(int(start), int(end)):
try:
subprocess.check_call(['ping', '-c', '2',
network + str(ip_address)],
stdout=FNULL,stderr=FNULL)
except (OSError, subprocess.CalledProcessError):
print ("{}{}".format(network,ip_address), "is down")
except KeyboardInterrupt:
print ("You halted the process")
sys.exit()
else:
print ("{}{}".format(network,ip_address), "is up")
return ip_address
check_up()
time1 = datetime.now()
time2 = datetime.now()
scantime = time2-time1
print ('Scan completed in: ', scantime)
while True:
print ('Would you like to write information to file?')
answer = input()
if answer in ['yes', 'y', 'yeah']:
print ('Alright, writing to file')
print ('Program will exit upon scan completion.')
break
elif answer in ['no', 'n']:
print ('Okay, exiting now..')
sys.exit()
break
else:
print ('Please enter a yes or no value')
###Output File
##with open('ipscan.txt', 'w+') as ip:
## print (ip_address, port)
##
##sys.exit()

subprocess: stdout and stderror seem interchanged or mixed

i'm trying to automate interactive ssh calls (see note 1) as follows:
SSHBINARY = '/usr/bin/ssh'
ASKPASS = '/home/mz0/checkHost/askpass.py'
def sshcmd(host,port,user,password,cmd):
env0 = {'SSH_ASKPASS': ASKPASS, 'DISPLAY':':9999'}
ssh = subprocess.Popen([SSHBINARY,"-T","-p %d" % port,
"-oStrictHostKeyChecking=no", "-oUserKnownHostsFile=/dev/null",
"%s#%s" % (user,host), cmd],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env0,
preexec_fn=os.setsid
)
error = ssh.stderr.readlines()
result = ssh.stdout.readlines()
return error,result
host = 'localhost'
port = 22
user = 'try1'
password = '1try' # unused, hardcoded in ASKPASS
cmd = 'ls'
result1, error1 = sshcmd(host,port,user,password,cmd)
if result1 : print "OUT: %s" % result1
if error1 : print "ERR: %s" % error1
It turns i'm doing something stupid since i get this:
OUT: ["Warning: Permanently added 'localhost' (RSA) to the list of known hosts.\r\n"]
ERR: ['['Desktop\n', ..., 'Videos\n']']
Obviously stdout and stderr are swapped (note 2). Can you kindly point me my error?
note 1: i'm well aware of password-less ssh, dangers of ignoring host key etc. and hate requests on automating interactive ssh as much as you.
note 2: running the same command in shell confirms that stdout and stderr are swapped in my code
ssh -o 'UserKnownHostsFile /dev/null' -o 'StrictHostKeyChecking no' \
try1#localhost ls > ssh-out 2> ssh-error
return error,result
and
result1, error1 = sshcmd(...)
Just swap either of those around.

How to check if $4 is registered in IRC?

I am quite an expert when it comes to programming in the MSL language, however I am unfamiliar with raw commands and whatnot.
I am in development of a new script. In this script I would like to check if $4 in what a user says is a registered nick or not but I do not know how to do this.
Thank you very much for any help and/or advice in advanced.
Best Regards,
Tim
Update:
raw 307:*:{ set $+(%,%chan,-,%CheckNick) Registered }
on *:TEXT:*:#:{
if ($1 == !regtest) {
set %chan $remove($chan,$chr(35))
set %CheckNick $4
whois $4
}
if ($($+(%,%chan,-,%CheckNick),$4),5) != $null) {
do this...
}
else {
else message...
}
}
I got this to work to check however my if statement to check if the variable has been set or not is being ignored...
Edit:
I tried using this:
checkNickReg $chan $2 $nick
...And echoing this:
echo -a Target: $1
echo -a Nick: $2
echo -a Status: $3
echo -a Chan: $3 - $chan
I'm trying to get a response to the channel such as; $nick $+ , $1 is not registered/registered/registered but not logged in.
What I've posted above is obviously wrong as it doesn't work, however I've tried a few methods and I'm actually not sure how the data is passed on with out the likes of tokenizing or setting variables...
Reply
[01:59:06] <~MrTIMarshall> !isReged mr-dynomite
[01:59:08] <&TornHQ> : mr-dynomite status is: NOTLOGGED
EDIT: mr-dynomite is not currently on, should this not = does not exist or does this check even when their not on, if so this is bloody brillant!!!
[02:00:04] <~MrTIMarshall> !isReged MrTIMarshall
[02:00:04] <&TornHQ> : MrTIMarshall status is: LOGGEDIN
$4 does not seem to work and what is the difference between 'exists, not logged in' and 'recognized, not logged in'?
Also, how does the data get passed on without setting variables or tokenizing?
(P.S. Thank you so much for the help you have dedicated so far!)
Another Edit:
I've been taking an in depth look today, am I correct in thinking if 0 or 1 the user is either not on-line or not registered (in the comments it says 0 = does not exists / not online, 1 = not logged in whereas 2 also says not logged in but recognized of which I'm unsure as what recognized means. Otherwise I'm very grateful for this script help and whatnot I'm just unclear on the numbers...
Since you have not specified any particular network I wrote an outline for some common networks around (that actually have user authentication systems). You should be able to add many other networks following the pattern.
Basically you execute /checkNickReg <target> <nick> [optional extra data] and when the server replays with the registration info (if applicable) use the on isReged signal event to handle the reply. Everything else is pretty much transparent.
EDIT: Looks like the specified network you are using (Torn) uses the standard anope services. So I updated the code to support that network.
; triggers when you get nick registration info back
; $1 = Target
; $2 = Nick
; $3 = Status, can be: LOGGEDIN, RECOGNIZED, NOTLOGGED
; $4- = Everything else passed
on *:signal:isReged:{
echo -a Target: $1
echo -a Nick: $2
echo -a Status: $3
echo -a Else: $4-
}
; reg lookup routines
alias checkNickReg {
set %reg. $+ $network 1
set %reg.target. $+ $network $1
set %reg.nick. $+ $network $2
set %reg.other. $+ $network $3-
; Freenode uses: NickServ ACC <nick>
if ($network == Freenode) msg NickServ ACC $2
; Rizon/SwiftIRC/OFTC/Torn use: NickServ STATUS <nick>
elseif ($istok(Rizon SwiftIRC OFTC Torn, $network, 32)) msg NickServ STATUS $2
}
; listen for replays
on *:notice:*:*:{
if ($($+(%, reg., $network),2)) {
;
var %target = $($+(%, reg.target., $network),2)
var %nick = $($+(%, reg.nick., $network),2)
var %other = $($+(%, reg.other., $network),2)
;
unset %reg*. $+ $network
if (($network == FreeNode) && ($2 == ACC)) $&
|| (($istok(Rizon SwiftIRC OFTC Torn, $network, 32)) && ($1 == STATUS)) {
; FreeNode:
; 0 = does not exist
; 1 = exists, not logged in
; 2 = recognized, not logged in
; 3 = logged in
; Rizon/SwiftIRC/OFTC/Torn:
; 0 = does not exists / not online
; 1 = not logged in
; 2 = recognized, not logged in
; 3 = logged in
if ($3 < 2) var %status = NOTLOGGED
elseif ($3 == 2) var %status = RECOGNIZED
else var %status = LOGGEDIN
}
;send status signal
.signal isReged %target %nick %status %other
}
}
(Extra Note: It might be useful to add an extra check to make sure $nick is AuthServ/NickServ for security reasons.)
A simple usage example is:
; Just a basic example of how to call it.
on *:text:!isReged &:#:{
checkNickReg $chan $2 $nick
}
on *:signal:isReged:{
msg $1 $4: $2 status is: $3
}
Type !isReged <nick>
Edit: The data gets passed to the on isReged event via global variables. I set them in the checkNickReg alias and I clean them up in the on notice event. So you never see them because they get cleaned up. They are passed to the isReged signal event in $1-.
On most IRCDs, it's only exposed in the WHOIS response for a user, if at all. Running a WHOIS every time a user says something is inadvisable, especially because server admins may receive a notification every time it happens.