def AddRoute(self, Destination, Mask, Interface, Gateway=None): try: self.log.increaseLevel() if Gateway == None: Gateway = "" GatewayText = "" else: GatewayText = "with gateway %s" % Gateway Gateway = " gw " + Gateway String1 = "route del -net " + Destination + " netmask " + Mask + Gateway if lib_Bash.Bash([String1]): pass else: self.log.printOK("removed existing duplicate route") String2 = "route add -net " + Destination + " netmask " + Mask + Gateway + " dev " + Interface if lib_Bash.Bash([String2]): self.log.printError( "add route Destination : %s Mask : %s on Interface : %s %s Failed" % (Destination, Mask, Interface, GatewayText)) self.log.decreaseLevel() return True else: self.log.printOK( "add route Destination : %s Mask : %s on Interface : %s %s Successfull" % (Destination, Mask, Interface, GatewayText)) self.log.decreaseLevel() except Exception as e: self.log.printError("error in adding route") self.log.printError("e")
def CheckHostname(INI): log = lib_Log.Log(PrintToConsole=True) log.printBoldInfo("Check Hostname") log.increaseLevel() INIHostname = INI.getOption("INFO", "VESSELNAME") if INIHostname != None: #cleanup hostname for forbidden characters INIHostname = re.sub(" ", "_", INIHostname) INIHostname = re.sub('[^a-zA-Z0-9_.]', '', INIHostname) #get hostname Hostname = subprocess.check_output(["hostname"]) Hostname = Hostname.strip().decode('ascii') if Hostname != INIHostname: log.printWarning("changing hostname from '%s' to '%s'" % (Hostname, INIHostname)) #adjust /etc/hosts CommandString = "sed -ie s/" + Hostname + "/" + INIHostname + "/g /etc/hosts" if lib_Bash.Bash(str(CommandString)): log.printError("Failed changing '/etc/hosts'") #adjust /etc/hostname CommandString = "sed -ie s/" + Hostname + "/" + INIHostname + "/g /etc/hostname" if lib_Bash.Bash(str(CommandString)): log.printError("Failed changing '/etc/hostname'") #reboot log.printWarning("Warning system will reboot in 20 seconds") time.sleep(20) os.system("sudo shutdown -r now") else: log.printInfo("Hostname is still correct")
def CreateOpenVPNFile(self): OpenVPNString = "" OpenVPNString += lib_Log.Banner() OpenVPNString += lib_Log.FileWarning() OpenVPNString += "client \n" OpenVPNString += "dev tun \n" OpenVPNString += "proto tcp \n" OpenVPNString += "remote 185.95.73.13 11999 \n" OpenVPNString += "resolv-retry infinite \n" OpenVPNString += "nobind \n" OpenVPNString += "persist-key \n" OpenVPNString += "persist-tun \n" OpenVPNString += "ca ./ca.crt \n" OpenVPNString += "cert ./rhbox" + IMO + ".crt \n" OpenVPNString += "key ./" + IMO + ".key \n" OpenVPNString += "ns-cert-type server \n" OpenVPNString += "comp-lzo \n" OpenVPNString += "log-append log/openvpn.log \n" OpenVPNString += "verb 3 \n" OpenVPNString += "keepalive 20 60 \n" try: OVPNFile = open("/etc/openvpn/rhbox_server.conf", 'w') OVPNFile.write(OpenVPNString) OVPNFile.close() except KeyboardInterrupt: self.log.printError("\nMain Program stopped by User (CTRL+C)") exit() except: self.log.printError("Error writing /etc/openvpn/rhbox_server.conf") if lib_Bash.Bash("service openvpn restart"): self.log.printError("could not restart openvpn") return return
def RestartInterfaces(self): self.log.printInfo("Restarting interfaces") if lib_Bash.Bash("sudo /etc/init.d/networking restart"): self.log.printError("Failed Restarting Network Interfaces") return True else: self.log.printOK("Network Interfaces Restarted")
def DelGateway(self,Metric = 1): Metric = str(Metric) with open(os.devnull, 'w') as DEVNULL: i = 0 while i<10: if lib_Bash.Bash("ip route del 0/0 metric " + Metric): self.log.printOK( "Gateways with metric %s removed"%Metric) break i += 1
def DelAllGateways(self): with open(os.devnull, 'w') as DEVNULL: i = 0 while i<10: if lib_Bash.Bash("ip route del 0/0"): self.log.printOK( "All Gateways removed") break i += 1
def DoPingTest(self, interface=None): Inf = "" if interface != None: Inf = "-I " + interface + " " if lib_Bash.Bash("ping " + Inf + "-c 1 " + self.IP): is_up = False else: is_up = True return is_up
def SetGateway(self,Gateway,Metric = 1): DNS = ["172.26.144.8","8.8.8.8","8.8.4.4"] self.SetDNS(DNS) Metric = str(Metric) # self.log.printError("route add default gw " + Gateway + " metric " + Metric) if lib_Bash.Bash("sudo route add default gw " + Gateway + " metric " + Metric): self.log.printError( "Failed to set Gateway") return True else: self.log.printOK("Gateway %s \tset with metric %s"%(Gateway,Metric))
def FlushFirewall(self): if lib_Bash.Bash([ "iptables -F", "iptables -X", "iptables -t nat -F", "iptables -t nat -X", "iptables -t mangle -F", "iptables -t mangle -X", "iptables -P INPUT ACCEPT", "iptables -P FORWARD ACCEPT", "iptables -P OUTPUT ACCEPT" ]): self.log.printError("/rhbox/bash/FlushFirewall.sh Failed") return True else: self.log.printOK("Successfully Flushed Firewall")
def PortForwarding(self, VPNPort, DestinationIP, DestinationPort, Description): Interface = "tun1" String1 = "iptables -t nat -A PREROUTING -i " + Interface + " -p tcp --dport " + str( VPNPort) + " -j DNAT --to " + DestinationIP + ":" + str( DestinationPort) String2 = "iptables -t nat -A POSTROUTING -p tcp -d " + DestinationIP + " --dport " + str( DestinationPort) + " -j MASQUERADE" if lib_Bash.Bash([String1, String2]): self.log.printError( "Set PortForward tun1:%s \t --> \t %s:%s \t Failed for %s" % (VPNPort, DestinationIP, DestinationPort, Description)) return True else: self.log.printOK( "Set PortForward tun1:%s \t --> \t %s:%s \t successfully set for %s" % (VPNPort, DestinationIP, DestinationPort, Description))
def RemoveVlans(self): if self.Error == False: try: self.Interfaces = {} interface = netifaces.interfaces() for vlan in interface: if vlan[0:4] == "vlan": self.log.printOK("%s removed" % vlan) if lib_Bash.Bash("sudo vconfig rem {0}".format(vlan)): self.log.printError("Failed removing %s" % vlan) return True else: self.log.printOK("%s removed" % vlan) except Exception as e: self.log.printError("GetVlans Failure") self.log.printError(e) self.Error = True
def SetPortforwarding(self): self.log.printBoldInfo("Portforwarding") self.log.increaseLevel() PortForwardingEnable = self.INI.getOptionBool("PORTFORWARDINGGENERAL", "PORTFORWARDINGENABLE") if PortForwardingEnable == None or PortForwardingEnable == False: self.log.printWarning( "Portforwarding option 'PortForwardingEnable' is not set") return True PortForwarding = self.INI.getOption("PORTFORWARDING") if PortForwarding is None: self.Error = True return True else: #Enable Portforwarding if lib_Bash.Bash("sysctl -w net.ipv4.ip_forward=1"): self.log.printError("Failed to enable Portforwaring") return True #set Portforwarding Rules for devNumber in PortForwarding: Description = self.INI.getOptionStr("PORTFORWARDING", devNumber, "DESCRIPTION") SourcePort = self.INI.getOptionInt("PORTFORWARDING", devNumber, "SOURCEPORT") DestinationPort = self.INI.getOptionInt( "PORTFORWARDING", devNumber, "DESTINATIONPORT") DestinationIP = self.INI.getOptionStr("PORTFORWARDING", devNumber, "DESTINATIONIP") if Description != None and SourcePort != None and DestinationPort != None and DestinationIP != None: self.PortForwarding(SourcePort, DestinationIP, DestinationPort, Description) return False
def Update(self,Program): """Get desired version from server """ self.log.printInfo("Get desired Gitversion") GitVersion = self.Exchange_Versions_With_Remote(Program) """Update GIT""" if self.Error == False: Force = Program + "_FORCE_LATEST" RebootDisable = True GitLocal = self.GITDir[Program] try: g = git.cmd.Git(GitLocal) OriginalGitVersion = g.describe("--tags") self.log.printInfo("Update %s GIT from version '%s' to version '%s'"% (Program,OriginalGitVersion,GitVersion)) forceUpdate = self.INI.getOptionBool("SOFTWARE_UPDATE",Force.upper()) if forceUpdate == None: forceUpdate = False if (OriginalGitVersion != GitVersion or forceUpdate == True or GitVersion == "latest" or GitVersion == "development"): g.reset('--hard') try: g.reset('--hard', "FETCH_HEAD") except: self.log.printWarning("reset --hard FETCH_HEAD for '%s' failed" % GitLocal) #Checking URL CurrentURL = g.remote ("-v") CurrentURL = CurrentURL.splitlines()[0] CurrentURL = CurrentURL.split() CurrentURL = CurrentURL[1] #get credentials from INI Password = self.INI.getOption("GIT_SERVER", "PASSWORD") Host = self.INI.getOption("GIT_SERVER", "HOST") User = self.INI.getOption("GIT_SERVER", "USER") URL = self.INI.getOption("GIT_SERVER", "URL") if URL != None and Host != None and User != None and Password != None: RemoteURL = "ssh://" + User + "@" + Host + ":" + URL + Program.lower() + ".git" #set correct git URL if CurrentURL != RemoteURL: g.remote("set-url", "origin", RemoteURL ) self.log.printWarning("changed URL from '%s' to '%s'" % (CurrentURL,RemoteURL)) if not lib_Bash.Bash ("sshpass -p %s git -C %s pull" % (Password,GitLocal)): if self.INI.getOptionBool("SOFTWARE_UPDATE",Force.upper()) == False and GitVersion != "latest" and GitVersion != "development": #Try to go to Specific Version as descibed by remote try: g.reset('--hard', GitVersion) self.log.printOK ("succesfully set %s version '%s'" % (Program,GitVersion)) except: self.log.printWarning ("GIT version '%s' is not found" % GitVersion) #Try to return to previous version" try: g.reset('--hard', OriginalGitVersion) self.log.printWarning ("Successfully rolled %s back to version '%s'" % (Program,OriginalGitVersion)) except: self.log.printWarning ("Original %s GIT version '%s' is not found" % (Program,OriginalGitVersion)) g.reset('--hard', "FETCH_HEAD") self.log.printWarning ("%s Went to latest available version in GIT" % Program) elif GitVersion == "development": DevelopVersion = g.describe("--tags") self.log.printInfo("%s Development version is selected by Server" % Program) self.log.printOK ("%s Went to latest available version '%s' in GIT" % (Program,DevelopVersion)) else: result = g.tag() Number = [] temp = result.split('\n') for line in temp: try: Version = parse("Version_{Mayor}.{Minor}.{Build}",line) Number.append(int(Version["Mayor"])) except: pass Mayor = max(Number) Number= [] for line in temp: try: Version = parse("Version_{Mayor}.{Minor}.{Build}",line) result = int(Version["Mayor"]) if result == Mayor: Number.append(int(Version["Minor"])) except: pass Minor = max(Number) Number= [] for line in temp: try: Version = parse("Version_{Mayor}.{Minor}.{Build}",line) result1 = int(Version["Mayor"]) result2 = int(Version["Minor"]) if result1 == Mayor and result2 == Minor: Number.append(int(Version["Build"])) except: pass Build = max(Number) LatestTag = "Version_%s.%s.%s"%(Mayor,Minor,Build) g.reset('--hard', LatestTag) if self.INI.getOptionBool("SOFTWARE_UPDATE",Force.upper()) == True: self.log.printWarning ("%s Forced to latest enabled by ini-file" % Program) else: self.log.printWarning ("%s Forced to latest enabled by ServerDatabase as desiredversion = '%s'" % (Program,GitVersion)) self.log.printOK ("%s Went to latest available version '%s' in GIT" % (Program,LatestTag)) else: RebootDisable = False self.log.printOK ("%s GIT does not require any update --> reboot disabled" % Program) except: self.log.printError ("Can not establisch GIT connection to remote") RebootDisable = False self.Error = True else: self.log.printError("%s skipped due to previous failure" % sys._getframe().f_code.co_name) self.Error = True self.log.printInfo("Push current Gitversion to Server for %s" % Program) self.Exchange_Versions_With_Remote(Program) return RebootDisable