Guest User

Untitled

a guest
May 23rd, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.24 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: latin1 -*-
  3. # A batch Interpreter for Linux
  4.  
  5. import os
  6. import time
  7. import sys
  8. import getpass
  9. import urllib
  10. import shutil
  11. import math # For square root and pi
  12. import ConfigParser # for reliable configs (ini-parsing eventually) :P (don't know much about ahm.. batch :P)
  13. # libraries to rebuild PAUSE()
  14. import termios
  15. import fcntl
  16. # libraries to rebuild ipconfig
  17. import socket
  18. import struct
  19. import urllib2 # global ip thing :)
  20. import array # for the listdevices() thing
  21. # powerful libraries for my own batch-like-language.
  22. import Image
  23. import ImageDraw
  24.  
  25. from random import randint as rint
  26.  
  27.  
  28. version = "0.1"
  29.  
  30. class Batch():
  31. def __init__(self):
  32. # writeDataToRam or sth else here
  33. global pointer
  34. global fileobj
  35. global environment
  36.  
  37. # special vars ++ Windows global Var ;)
  38. self.loudly = "on"
  39. self.more_output = 0
  40. self.sexyCode = 0
  41. self.cLineNumber = "Display :0.0"
  42. self.vars = (
  43. {"%windir%":"sys/Windows/",
  44. "%TEMP%":"sys/Windows/Temp",
  45. "%USER%":str(getpass.getuser()),
  46. "%ALLUSERPROFILE%":"sys/Users/public",
  47. "%APPDATA%":"sys/Users/"+str(getpass.getuser())+"/.App_Data",
  48. "%CLIENTNAME%":"Python Batch Interpreter",
  49. "%COLORTERM%":"gnome-terminal", # ksh, sh, comexshell and wtf. change it if you doesn't have gnome-term.
  50. "%CommonProgramFiles%":"sys/Programs/CommonProgramFiles/",
  51. "%ComSpec%":"sys/Windows/syscmd.py",
  52. "%DISPLAY%":":0.0",
  53. "%HOMEDRIVE%":"sys/",
  54. "%PATH%":os.getcwd(),
  55. "%HOMEPATH%":"sys/Users/"+str(getpass.getuser())+"/",
  56. "%LANG%":"de_DE.latin1", # dont blame me latin ;)
  57. # the %0 var is powerful :) ->
  58. "%0":os.getcwd()+"/"+__file__,
  59. "%cCurrentLine%":"0", # and another very nice var :)
  60. }
  61. )
  62. def version(self):
  63. return version#0.1
  64. def sleep(self, t = ""):
  65. """A feature for Batch0.2 for Python - not winBatch"""
  66. if not t:
  67. print "ERROR; sleep() needs at least 1 Parameter"
  68. return 0
  69. time.sleep(t)
  70. def more(self, file = ""):
  71. if not os.path.isfile(file):
  72. print "more: Datei %s existiert nicht" % (file)
  73. return 0
  74. f = open(file, "r")
  75. lines = f.readlines()
  76. for line in lines:
  77. print line,
  78. if self.sexyCode == 1:
  79. print
  80. def mkdir(self, dirname):
  81. if os.path.isdir(dirname):
  82. print "{Error:Line #%s} mkdir [Dir already exists][File: %s]" % (self.cLineNumber,self.cFileName)
  83. sys.exit(-1)
  84. os.mkdir(dirname)
  85. def open(self, file = ""):
  86. if not file:
  87. print "Syntax: %s <DATEI>" % (__file__)
  88. return 0
  89. if not os.path.isfile(file):
  90. print "Datei: %s konnte nicht gefunden werden. [%s]" % (file,os.getcwd())
  91. return 0
  92.  
  93. f = open(file, "r")
  94. self.cLineNumber = 0
  95. lines = f.readlines()
  96. self.cFileName = file
  97. for line in lines:
  98. self.cLineNumber += 1
  99. self.vars["%cCurrentLine%"] = str(int(self.vars["%cCurrentLine%"])+1)
  100. lx = line.split("\n")[0] # fixes a big bug
  101. line = lx.split(" ")
  102. if os.path.isfile("sys/Windows/"+line[0].split("\n")[0]+".py"):
  103. execfile("sys/Windows/"+line[0].split("\n")[0]+".py",{"ARGUMENTS":" ".join(line[1:]).replace("\n","")})
  104. elif line[0] == "pause" or line[0] == "pause\n":
  105. self.pause()
  106. elif line[0] == "@echo":
  107. if line[1] == "off":
  108. self.loudly = "off"
  109. else:
  110. print self.status()
  111. elif line[0] == "more":
  112. self.more(line[1].split("\n")[0])
  113. elif line[0] == "echo":
  114. self.echo(" ".join(line[1:]))
  115. elif line[0] == "goto":
  116. if line[1]:
  117. print "Goto: %s" % (line[1])
  118. else:
  119. print "Keine Sektion"
  120. elif line[0] == "copy":
  121. self.copy(self.decodevars(line[1]),self.decodevars(line[2].split("\n")[0]))
  122. elif line[0] == "exit":
  123. sys.exit(-1)
  124. elif line[0] == "set":
  125. varstring = ' '.join(line[1:])
  126. varstring = varstring.split("=")
  127. value = varstring[1]
  128. var = varstring[0]
  129. value = value.split("\n")[0]
  130. self.set(self.decodevars(var),self.decodevars(value))
  131.  
  132. def copy(self, file,target):
  133. shutil.copy(file,target)
  134. if self.loudly != "off":
  135. print "Kopiere Datei %s nach %s" % (file,target)
  136.  
  137. def imaging(self, file=""):
  138. img = Image.new("RGB",(300,300),"#000000")
  139. draw = ImageDraw.Draw(img)
  140.  
  141. r,g,b = rint(0,255), rint(0,255), rint(0,255)
  142. dr = (rint(0,255) - r)/300
  143. dg = (rint(0,255) - g)/300
  144. db = (rint(0,255) - b)/300
  145. for i in range(300):
  146. r,g,b = r+dr, g+dg, b+db
  147. draw.line((i,0,i,300),fill=(int(r),int(g),int(b)))
  148. img.save("line.png","PNG")
  149.  
  150. def decodevars(self, text = ""):
  151. for i in self.vars:
  152. if i in text:
  153. text = text.replace(i,self.vars[i])
  154. return text
  155.  
  156. def echo(self, text = "", params = []):
  157. """The echo-Rebuild"""
  158. # text = string [>> file]
  159. if text.count(">") == 1 or text.count(">>") == 1:
  160. if text.count(">") == 1:
  161. os.system("echo \"%s\" > \"%s\"" % (text.split(" > ")[0],text.split(" > ")[1]))
  162. pass
  163. elif text.count(">>") == 1:
  164. # text.count(">") triggered before so we don't need to retry
  165. os.system("echo \"%s\" >> \"%s\"" % (text.split(" >> ")[0],text.split(" >> ")[1]))
  166. pass
  167. if not text:
  168. print "{Error:Line #%s} echo [No Text to output][File: %s]" % (self.cLineNumber,self.cFileName)
  169. sys.exit(-1)
  170. return 0
  171. if self.loudly == "on":
  172. print "echo %s" % (text),
  173. print self.decodevars(text)
  174.  
  175.  
  176. def set(self, var, value):
  177. #print "DEBUG: set [NOPARAM] %s zu %s" % ("%" + var + "%", value)
  178.  
  179. self.vars["%"+str(var)+"%"] = str(value)
  180. # "%" fixes many bugs :) so you can not set HELLO="Bye" to stop posting HELLO Texts ;)
  181.  
  182. def silent(self, type = "on"):
  183. if type == "off":
  184. self.loudly = "off"
  185. else:
  186. self.loudly = type
  187.  
  188. def status(self):
  189. return self.loudly
  190.  
  191. def clear(self):
  192. if os.name == "posix":
  193. os.system("clear")
  194. else:
  195. print "\n"*100
  196. # sessions (new! :))
  197. def newSession(self, sessionname = ""):
  198. print "Konnte keine Session starten.."
  199. print "Dies kann folgende Gruende haben:\n"
  200. print "Sessions sind noch nicht implementiert oder verfuegbar!"
  201. print "Die Session.uix Datei scheint veraltet zu sein"
  202. print "Die aktuelle Konfiguration verhindert Sessions"
  203.  
  204. def saveSession(self, sessionname = ""):
  205. """A feature for Batch0.2 for Python - not winBatch
  206. You can save the whole ScriptData (vars, output and so on)
  207. You can use getSession(name) to get the Data running for YOUR Session"""
  208. # beta: store all your arrays in a File
  209. if self.more_output:
  210. print "Starte Datenspeicherung - %s" % (sessionname)
  211. d = open("session.uix","w")
  212. d.write("[cvars]")
  213. for item in self.vars:
  214.  
  215. value = self.vars[item]
  216. d.write("\n" + item + "=" + value)
  217. if self.more_output:
  218. print "Speichere %s | WertSpiegel: %s" % (item, value)
  219. d.write("\n[uix]\nos.name=" + str(os.name))
  220. d.close()
  221. if self.more_output:
  222. print "Session stored.."
  223. def getSession(self):
  224. d = open("session.uix","r")
  225. a = d.readlines()
  226. for i in a:
  227. if i.count("%") > 1:
  228. self.vars[i.split("=")[0]] = i.split("=")[1].replace("\n","")
  229.  
  230. def pause(self, allow_every_key = 1):
  231. """The pause-Rebuild, loops til' it returns an exception"""
  232. if allow_every_key == 1:
  233. self.pause_text = "eine Taste"
  234. else:
  235. self.pause_text = "Enter"
  236.  
  237. fd = sys.stdin.fileno()
  238. oldterm = termios.tcgetattr(fd)
  239. newattr = termios.tcgetattr(fd)
  240. newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
  241. termios.tcsetattr(fd, termios.TCSANOW, newattr)
  242.  
  243. oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
  244. fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
  245. print "Druecke %s um fortzufahren..." % (self.pause_text)
  246. try:
  247. while 1:
  248. try:
  249. if allow_every_key == 1:
  250. c = sys.stdin.read(1)
  251. break
  252. else:
  253. c = sys.stdin.read(1)
  254. if c == "\n": break
  255. except IOError: pass
  256. finally:
  257. termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
  258. fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
  259.  
  260.  
  261.  
  262. if __name__ == "__main__":# You really need this cause the UpdateManager starts itself using other__name__
  263. B = Batch() # child born! yeah 8)
  264. # STOP! This Code isn't finished yet.
  265.  
  266. # THE VISUAL BATCH SHELL! - THE INTERPRETER IS THE .open() Function (the .open() Function may be older)
  267. try:
  268. if os.path.isfile(sys.argv[1]):
  269. if B.status() == "on":
  270. #print "Execute Batch-File: %s" % (sys.argv[1])
  271. d=0
  272. B.open("example.bat")
  273. except IndexError:
  274. print ">> Batch %s for Linux started!\n" % (version)
  275. prompt = ">> "
  276. while True:
  277. try:
  278. d = raw_input(prompt ).split(" ")
  279. except:
  280. print "Programmabbruch mit STRG + C nicht möglich!\nGebe: \"exit\" ein um das Programm sanft zu beenden"
  281. continue
  282.  
  283. if d[0] == "":
  284. pass
  285. elif os.path.isfile("sys/Windows/"+d[0]+".py"):
  286. execfile("sys/Windows/"+d[0]+".py")
  287. elif d[0] == "more" or d[0] == "type":
  288. try:
  289. B.more(d[1])
  290. except IndexError:
  291. B.more()
  292. elif d[0] == "start":
  293. if len(d) < 2:
  294. B.newSession()
  295. else:
  296. B.open(d[1])
  297. elif d[0] == "ipconfig\all" or d[0] == "ipconfig" and d[1] == "all":
  298. execfile("sys/Windows/ipconfig.py")
  299. elif d[0] == "exit":
  300. sys.exit(-1)
  301. #elif d[0] == "ipconfig":
  302. # execfile("sys/Windows/ipconfig.py")
  303. elif d[0] == "ImageProcessing":
  304. print "Generate Image.."
  305. B.imaging()
  306. elif d[0] == "@echo":
  307. # suitable output command
  308. try:
  309. B.silent(d[1])
  310. except:
  311. print "@echo =",B.status()
  312. elif d[0] == "echo":
  313. B.echo(" ".join(d[1:]))
  314. elif d[0] == "pause":
  315. B.pause()
  316. elif d[0] == "saveSession":
  317. B.saveSession()
  318. elif d[0] == "getSession":
  319. B.getSession()
  320. elif d[0] == "cls": #clear() :)
  321. if os.name == "posix":
  322. os.system("clear")
  323. else:
  324. print "\n"*100
  325. elif d[0] == "set":
  326. if d[1] == "/p":
  327. varname = d[2].split("=")[0].replace("%","")
  328. print ">> ",
  329. value = raw_input()
  330. B.set(varname,value)
  331. else:
  332. B.set(d[1].split("=")[0],d[1].split("=")[1])
  333. elif d[0] == "prompt":
  334. try:
  335. prompt = " ".join(d[1:])
  336. except IndexError:
  337. prompt = ">> "
  338. else:
  339. print "Unbekanntes Kommando: %s (Eventuell noch nicht geportet)" % (d)
  340. pass
  341.  
  342. # Details:
  343. man = ("""
  344. The following applications are already ported:
  345. prompt => Change the String in Shell-Mode
  346. more => Read Text from File
  347. cls => Clear the Shell-Mode Screen (works even in windows through 100 LineBreaks)
  348. echo => Write Text to Shell-Window (even >,>> works now! =))
  349. pause => Hold the Screen and wait for a Key (You can switch between EVERY KEY and JUST ENTER in the Config)
  350. start => Start a new File/Session in Shell-Mode
  351. exit => Exit the Shell-Mode Window (+Script)
  352. copy => A simple File-Copy Script (Not many options here, but you can also do the copy %0 %0.bak shit :)
  353. @echo => Silent/Loud-Mode (if @echo on, the Script will post a Copy of the Command which gets executed.)
  354. Set => A minimal set Function, works like this: set %VAR%=VALUE. :) (Next feature: set /p for UserInput)
  355. sleep => Not a feature in "shell", but a create debugging Tool.
  356. ipconfig => Ported now! Linked /all to the default Client. :)
  357. ---------------------------------------------------------------
  358. In the next release:
  359. set /p => For a User Input Variable | works now ;), next thing is to port other set{} Things.
  360. more -nLINENUMBER <file> => To just read #N Lines in File
  361. help => The create help-Command :)
  362. ftp => The FTP-Client (hohh...)
  363. ----------------------------------------------------------------
  364. I can not port the following Applications cause they still need Windows:
  365. reg (The whole Registry-Thing, I try to 'PORT' just a few Things to my Linuxbox
  366. map (Hmm, I'm too stupid to get the network-devices.
  367. ------------------------
  368. Not sure to port:
  369. while (A hard way to port.. WHILEO.o)
  370. goto (Just.. annoying ;)) """)
Add Comment
Please, Sign In to add comment