Connection refused - Python 2.7 - python

I am trying to run the python code in the linux machine where the weblogic server is located whose health status needs to be known. I am passing username and password as per below code. Below is part of the python code:
import urllib2
import httplib
import getpass
import json
import os
import sys
import time
import math
def getServerJson(url, username, password):
req = urllib2.Request(url)
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
try:
response = opener.open(url)
json_string = response.read()
if response.getcode() != 200:
print("")
print("Error connecting to WLS Server!")
print("HTTP Error code = " + str(response.getcode()))
print("URL = "+url)
sys.exit(1)
except urllib2.URLError as e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
except urllib2.HTTPError, e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
except httplib.HTTPException, e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
return json.loads(json_string)
But I am getting below error on giving input:
Please enter the WLS Server Details
Please enter the server and port: IP:PORT
Please enter the weblogic user name: weblogic
Please enter the weblogic user password:
[Errno 111] Connection refused
Please find below the url calling part of the code:
def getServerJson(url, username, password):
req = urllib2.Request(url)
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
try:
response = opener.open(url)
json_string = response.read()
if response.getcode() != 200:
print("")
print("Error connecting to WLS Server!")
print("HTTP Error code = " + str(response.getcode()))
print("URL = "+url)
sys.exit(1)
except urllib2.URLError as e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
except urllib2.HTTPError, e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
except httplib.HTTPException, e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
return json.loads(json_string)
#Get a list of all of the Admin and Managed Servers in the domain
def getServers(wlsDomain,wlsServerUrl,username,password ):
url = 'http://'+wlsServerUrl+'/management/wls/latest/servers'
serverJson = getServerJson(url, username, password)
for server in serverJson["links"]:
if (server['rel'] != "parent"):
wlsDomain.addServer(WLSServer(server["title"], server["uri"]))
# Get the url of the list of logs, along with some other basic
# server information
def getLogListUrl(server, username, password):
serverJson = getServerJson(server.serverUrl, username, password)
server.setState(serverJson["item"]["state"])
if server.state == "running":
server.setHealth(serverJson["item"]["health"]["state"])
for link in serverJson["links"]:
if link["rel"] == "logs":
logListULR = link["uri"]
return logListULR
#For the given server, get the url for each server log
def getServerLogUrl(server,username,password, logListUrl):
logListJson = getServerJson(logListUrl, username, password)
for link in logListJson["links"]:
if link["rel"] == "items.name":
if not link["title"].startswith("JMSMessageLog") and \
not link["title"].startswith("HTTPAccessLog"):
server.addLog(WLLog(link["title"],link["uri"]))
#Go and find all server logs and read them, and take note of
#the error messages
def searchServerLogs(wlsDomain, username, password):
for server in wlsDomain.serverList:
#get the url to the list of logs for the given server
logListUrl = getLogListUrl(server, username, password)
#we can't get the log of a server that is not running
if server.state != "running":
continue
#get the url for each server log of the given server
getServerLogUrl(server,username,password, logListUrl)
for log in server.logList:
#we are not interested in the HTTPAccessLog
if log.name != "HTTPAccessLog":
if server.state != "running":
continue
startTime = time.time()
print("Reading " + server.name + " : " + log.name)
serverLogJson = getServerJson(log.logUrl, username, password)
for logEntry in serverLogJson["items"]:
if logEntry["severity"] == "Error":
log.addLogEntry(LogEnty(logEntry["severity"],logEntry["timeStamp"],logEntry["message"]))
server.incrementError()
endTime = time.time()
log.setDuration(formatTimeOutput(math.floor(endTime-startTime)))
def run():
print("")
print("")
print("Please enter the WLS Server Details")
print("-------------------------------------------")
print("")
wlsServerUrl = raw_input('Please enter the server and port e.g localhost:7001 ')
username = raw_input("Please enter the weblogic user name: ")
password = getpass.getpass("Please enter the weblogic user password: ")
print("")
wlsDomain = WLSDomain()
getServers(wlsDomain,wlsServerUrl,username,password)
searchServerLogs(wlsDomain,username,password)
outputStatisticsConsole(wlsDomain)
writeHTMLOutput(wlsDomain)

Related

Why is python with Tipeeestream api not working?

im am trying to login in my Tipeeestream Account using the Tipeeestream Api key. But its not working(i got message:forbidden). Here is my code:
import sys
import requests
if len(sys.argv) != 5:
print("Usage: python " + sys.argv[0] + " <apiKey> <provider> <access_token> <refresh_token>")
exit()
apikey = sys.argv[1]
provider = sys.argv[2]
access_token = sys.argv[3]
refresh_token = sys.argv[4]
print("Getting username")
try:
r = requests.get('https://api.tipeeestream.com/v1.0/me?apiKey=' + apikey)
if "username" in r.json():
username = r.json()["username"]
print("Username " + username)
data = {
"access_token": access_token,
"origin": "managementSecurity",
"provider": provider,
"refresh_token": refresh_token
}
try:
r = requests.post('https://www.tipeeestream.com/v1.0/users/' + username + '/providers?apiKey=' + apikey, json=data)
print(r)
if "code" in r.json():
if r.json()["code"] == 200:
print("Log in to " + username)
else:
print("Error by loging in " + username)
else:
print("Error by loging in " + username)
except:
print("Error by loging in " + username)
except:
print("Error by getting username")
I have no idea how to fix it. I hope you can help me...

How to get data from database ( github )

This is what I have written for hwid authentication:
try:
current_machine_id = subprocess.check_output('wmic csproduct get uuid').decode().split('\n')
[1].strip()
r = requests.get('https://github.com/reactxsw/hwiddump/blob/main/hwid.txt')
except:
print('Error : Internet connection')
b = input('')
time.sleep(2)
def Authenticator():
if not current_machine_id in r.text:
print('Error : HWID not in database')
print(f'Invalid HWID :' + current_machine_id)
a = input('')
time.sleep(5)
exit()
else:
print("Permission granted !")
return True
Authenticator()
This takes the hwid which is stored in github. I wanted to have a username for each and every hwid.
So I have to do something like 00000000-0000-0000-0000-00D86152166F = REACT in the.txt I want to make a code which checks for hwid and take the name.
Do a GET request on raw text URL.
Below is the revised code:
try:
current_machine_id = subprocess.check_output('wmic csproduct get uuid').decode().split('\n')
[1].strip()
r = requests.get('https://raw.githubusercontent.com/reactxsw/hwiddump/main/hwid.txt')
uuids = r.text.strip().split("\n")
users = {}
for i in uuids:
users[i.split("=")[0].strip()] = i.split("=")[1].strip()
except:
print('Error : Internet connection')
b = input('')
time.sleep(2)
def Authenticator():
if not current_machine_id in uuids:
print('Error : HWID not in database')
print(f'Invalid HWID :' + current_machine_id)
a = input('')
time.sleep(5)
exit()
else:
print(f'Hello {users[current_machine_id]}')
print("Permission granted !")
return True
Authenticator()

How to prevent the script from being canceled when you receive a proxy server error

Can anyone guide me? How can I prevent my script from being completely canceled when I receive a proxy server error?
def proxy_on(self, email, password):
if proxy_on_of == "y":
#open proxy file
prox = open(proxy_file, "r").readlines()
cleaned_prox = [items.rstrip() for items in prox]
random_proxy = choice(cleaned_prox)
p_http = {"http": random_proxy,"https": random_proxy}
p_sock4 = {"http": "socks4://" + random_proxy,"https":"socks4://" + random_proxy}
p_sock5 = {"http":"socks5://" + random_proxy,"https":"socks5://" + random_proxy}
#Proxy Type
if proxy_type == "1":
proxy = p_http
elif proxy_type == "2":
proxy = p_sock4
elif proxy_type == "3":
proxy = p_sock5
#requests ready
session = requests.session()
try:
session.get("https://www.crunchyroll.com", proxies = proxy, timeout = 60)
except requests.exceptions.ProxyError as err:
print("Proxy Not Working: " + random_proxy)
else:
break
As you can see, probe with the exception "ProxyError", but the result was null
You can put your try except in a while loop to continue until the session.get receives an answer and continue the while loop in the except

LDAP uid path not known

Here there my working python script:
#!/usr/bin/python
import ldap, sys
l = ldap.initialize('ldap://myldapserver:389')
username = "uid=%s,OU=folder1,OU=myCompany,O=MyCompanyGroup" % "myID"
password = "mypassword"
try:
l.protocol_version = ldap.VERSION3
l.simple_bind_s(username, password)
valid = True
print "OK"
l.unbind()
except Exception, error:
print error
Now I would like to bind the user, just only specifying "O=MyCompanyGroup", and searching for the uid on that subtree. For example I can filter based on "inetOrgPerson"
I tried
username = "(&(objectClass=inetOrgPerson )(uid=%s)(O=MyCompanyGroup))" % "myID"
but I get Invalid credentials.
Thanks!
Riccardo
Found the solution
#!/usr/bin/python
import ldap, sys
l = ldap.initialize('ldap://myldapserver:389')
search_filter = "(&(uid=myID)(objectClass=inetOrgPerson))"
base_dn="O=MyCompanyGroup"
password = "mypassword"
try:
l.protocol_version = ldap.VERSION3
result = l.search_s(base_dn, ldap.SCOPE_SUBTREE, search_filter, None)
user_dn = result[0][0]
print user_dn
l.simple_bind_s(user_dn, password)
valid = True
print "OK"
l.unbind()
except Exception, error:
print error
Good technique #Riccardo79
In my case, I was forced to login as the admin of the LDAP first to performe the user password check.
Here is my code :
import ldap
ldap_admin_dn = "cn=admin..."
ldap_admin_password = "..."
ldap_users_dn="ou=to,ou=my,ou=users..."
def connectLDAP(self, username, password) -> bool:
search_filter = "(&(uid={})(objectClass=inetOrgPerson))".format(username)
try:
connection = ldap.initialize(self.ldap_endpoint)
connection.protocol_version = ldap.VERSION3
connection.simple_bind_s(ldap_admin_dn, ldap_admin_password)
result = connection.search_s(ldap_users_dn, ldap.SCOPE_SUBTREE, search_filter)
user_dn = result[0][0]
connection.simple_bind_s(user_dn, password)
connection.unbind()
except ldap.LDAPError as e:
print(e)
return False
return result

Various connection via telnet with/without password

import telnetlib
import os
import re
current_dir = os.getcwd()
IP = <IP>
def login_as_root():
print "logging in as root..."
tn.read_until("login: ")
tn.write("root\r")
response = tn.expect([re.compile(b"Password:"),b"root#",])
if "Password:" in response[2]:
send_msg("root", "root#")
else:
print "logging without passwd"
def send_msg(msg, wait_str, print_msg=0):
if print_msg:
print msg
tn.write("%s\n" % msg)
return tn.read_until(wait_str)
def launch_update():
try:
print send_msg("mount -o remount,rw /", "root# ", print_msg=1)
except:
Exception("Update configuring is failed")
def main():
global tn
try:
tn = telnetlib.Telnet(IP)
login_as_root()
except:
raise Exception("Connect failed")
launch_update()
if __name__ == "__main__":
main()
Need help with login_as_root(). There are 2 cases to login as root: with password and without any password. I have to connect correctly to host and then launch several commands in launch_update(). Script stucks after mount command.

Categories