当前位置:   article > 正文

crt批量增加session模板与脚本_crt.session

crt.session
  1. hostname,protocol,username,folder,session_name
  2. 172.20.0.1,SSH2,admim,test,test01
  3. 172.20.0.2,SSH2,admim,test,test02
  4. 172.20.0.1,SSH2,admim,test,test03
  1. # $language = "Python"
  2. # $interface = "1.0"
  3. # ImportArbitraryDataFromFileToSecureCRTSessions.py
  4. # (Designed for use with SecureCRT 7.2 and later)
  5. #
  6. # Last Modified: 29 Oct, 2018
  7. # - Change behavior to prompt individuals if they want new
  8. # session settings to derive from the "Default" session or
  9. # use this script's customizations.
  10. #
  11. # Last Modified: 23 Jul, 2018
  12. # - As some may have modified the Default session's protocol to
  13. # something incompatible with various options, the defaulting of
  14. # some options for imported sessions is now wrapped in error
  15. # suppressing tags to avoid the script bombing out if the default
  16. # session isn't SSH1/SSH2.
  17. # - This script example no longer enables templated log file naming
  18. # for imported sessions. This default behavior had created some
  19. # confusion for individuals who had configured their Default
  20. # session with a templated log file name because the prior version
  21. # of this script exemplified setting the value of the log file
  22. # name field for imported sessions to a templated log file name
  23. # that was different from what the individual had set in the Default
  24. # session. The code is still present, but it is commented out.
  25. # Search below for "Log Filename V2" if you want to see where to re-
  26. # enable it for your specific import objectives.
  27. #
  28. # Last Modified: 16 May, 2018
  29. # - Add a section to the results log that shows lines that weren't
  30. # imported. Lines are shown in a way that makes it easier to re-
  31. # run the script to import those lines after they've been modified
  32. # to correct any issues idendified (missing fields, too many fields,
  33. # disallowed characters in folder or session name, etc.) Also
  34. # modified the results log to have a formatting that more closely
  35. # matches that of the vbscript version to provide more consistency
  36. # when running the script regardless of the platform.
  37. # - Set session options for all imported sessions to reflect commonly
  38. # desired configurations (color scheme, anti-idle, log file naming,
  39. # larger scrollback buffer, etc.)
  40. # - Validate both folder paths and session names to prevent errors
  41. # that would normally stop the script. Report such failures at the
  42. # end of the scipt rather than halting the script in media res.
  43. # This validation includes preventing any attempts to name a session
  44. # with any disallowed character or illegal name (CON, PRN, AUX, NUL,
  45. # etc.)
  46. #
  47. # Last Modified: 23 Feb, 2018
  48. # - Info-blurb about sessions that were created during the import was
  49. # missing from the results log
  50. # - If running on Windows, and unable to write to results log, make
  51. # sure clipboard data containing the results log info is formatted
  52. # with \r\n instead of just \n so that it's legible in Notepad, for
  53. # example, when pasted.
  54. #
  55. # Last Modified: 21 Dec, 2017
  56. # - Allow multiple 'description' fields on the same line. All will be
  57. # compounded together with each one ending up on a separate line in
  58. # the Session's Description session option.
  59. # - Allow 'username' field to be defaulted in the header line
  60. # - Duplicate sessions are now imported with unique time-stamped
  61. # names (for each additional duplicate). Earlier versions of this
  62. # script would overwrite the first duplicate with any subsequent
  63. # duplicates that were found in the data file.
  64. # - Allow header fields to be case-insentive so that "Description"
  65. # and "HostName", etc. work just as well as "description" and "hostname"
  66. #
  67. # Last Modified: 18 Dec, 2017
  68. # - Remove unused (commented out) code block left in from the
  69. # 20 Apr, 2017 changes.
  70. # - Fix required header line message to no longer reference
  71. # 'protocol' field as required.
  72. # - Add fallback locations where the script will attempt to
  73. # write summary log of script's activities/errors/warnings.
  74. # This attempts to facilitate running this script in environments
  75. # where SecureCRT may not have access to a "Documents" folder
  76. # (such as when SecureCRT is being launched through VDI publishing).
  77. # --> First try Documents,
  78. # --> Then try Desktop,
  79. # --> Then try SecureCRT's config folder.
  80. # --> If none of the above are accessible for writing, the
  81. # script will copy the summary report to the clipboard,
  82. # providing the user with a way to see the summary report
  83. # if pasted into a text editor.
  84. # - Added support for defaulting the "folder" header so that all
  85. # new entries could be imported into a folder w/o having to
  86. # specify the folder on each line. Example header line for
  87. # CSV file with only hostname data would be:
  88. # hostname,folder=default_import_folder_name
  89. #
  90. # Last Modified: 17 Nov, 2017
  91. # - No longer attempt to use platform to determine OS ver info,
  92. # as it's no longer needed.
  93. #
  94. # Last Modified: 20 Apr, 2017
  95. # - No longer require protocol in header. Use the Default session's
  96. # protocol if the protocol field is not present in the header line.
  97. # - Conform to python join() method requiring only one argument.
  98. # - Prompt for delimiter character if it isn't found in the header line.
  99. # - Allow delimiter character to be NONE, so that a single field (hostname)
  100. # and corresponding data can be used to import sessions (say for example
  101. # if you have a file that just contains hostnames, one per line).
  102. # - [Bug Fix]: can't use + to concatenate str and int, so use format()
  103. # instead.
  104. # - [Bug Fix]: "Procotol" typo fixed to "Protocol" in error case where
  105. # protocol header field not found/set.
  106. #
  107. # Last Modified: 04 Jan, 2017
  108. # - Added support for specifying logon script file to be set for
  109. # imported sessions.
  110. #
  111. # Last Modified: 02 Jul, 2015
  112. # - Display status bar info for each line we're processing so that if
  113. # there's an error, the individual running the script might have
  114. # better information about why the error might have occurred.
  115. # - Handle cases where a line in the data file might have more fields
  116. # in it than the number of header fields designated for import. This
  117. # fixes an error reported by forum user wixxyl here:
  118. # https://forums.vandyke.com/showthread.php?t=12021
  119. # If a line has too many fields, create a warning to be displayed
  120. # later on, and move on to the next line -- skipping the current line
  121. # because it's unknown whether the data is even valid for import.
  122. #
  123. # Last Modified: 20 Jan, 2015
  124. # - Combined TAPI protocol handling (which is no longer
  125. # supported for mass import) with Serial protocol
  126. # import errors.
  127. # - Enhanced example .csv file data to show subfolder specification.
  128. #
  129. # Last Modified: 21 Mar, 2012
  130. # - Initial version for public forums
  131. #
  132. # DESCRIPTION
  133. # This sample script is designed to create sessions from a text file (.csv
  134. # format by default, but this can be edited to fit the format you have).
  135. #
  136. # To launch this script, map a button on the button bar to run this script:
  137. # http://www.vandyke.com/support/tips/buttonbar.html
  138. #
  139. # The first line of your data file should contain a comma-separated (or whatever
  140. # you define as the g_strDelimiter below) list of supported "fields" designated
  141. # by the following keywords:
  142. # -----------------------------------------------------------------------------
  143. # session_name: The name that should be used for the session. If this field
  144. # does not exist, the hostname field is used as the session_name.
  145. # folder: Relative path for session as displayed in the Connect dialog.
  146. # hostname: The hostname or IP for the remote server.
  147. # protocol: The protocol (SSH2, SSH1, telnet, rlogin)
  148. # port: The port on which remote server is listening
  149. # username: The username for the account on the remote server
  150. # emulation: The emulation (vt100, xterm, etc.)
  151. # description: The comment/description. Multiple lines are separated with '\r'
  152. # logon_script: The full path to the Logon Script filename for the session.
  153. # =============================================================================
  154. #
  155. #
  156. # As mentioned above, the first line of the data file instructs this script as
  157. # to the format of the fields in your data file and their meaning. It is not a
  158. # requirement that all the options be used. For example, notice the first line
  159. # of the following file only uses the "hostname", "username", and "protocol"
  160. # fields. Note also that the "protocol" field can be defaulted so that if a
  161. # protocol field is empty it will use the default value.
  162. # -----------------------------------------------------------------------------
  163. # hostname,username,folder,protocol=SSH2
  164. # 192.168.0.1,root,_imported,SSH1
  165. # 192.168.0.2,admin,_imported,SSH2
  166. # 192.168.0.3,root,_imported/folderA,
  167. # 192.168.0.4,root,,
  168. # 192.168.0.5,admin,_imported/folderB,telnet
  169. # ... and so on
  170. # =============================================================================
  171. import datetime
  172. import os
  173. import platform
  174. import re
  175. import shutil
  176. import sys
  177. import time
  178. import subprocess
  179. MsgBox = crt.Dialog.MessageBox
  180. # The g_strDefaultProtocol variable will only be defined within the
  181. # ValidateFieldDesignations function if the protocol field has a default value
  182. # (e.g., protocol=SSH2), as read in from the first line of the data file.
  183. global g_strDefaultProtocol
  184. g_strDefaultProtocol = ""
  185. # The g_strDefaultFolder variable will only be defined within the
  186. # ValidateFieldDesignations function if the folder field has a default value
  187. # (e.g., folder=Site34), as read in from the first line of the data file.
  188. global g_strDefaultFolder
  189. g_strDefaultFolder = ""
  190. # The g_strDefaultUsername variable will only be defined within the
  191. # ValidateFieldDesignations function if the protocol field has a default value
  192. # (e.g., username=bobofet), as read in from the first line of the data file.
  193. global g_strDefaultUsername
  194. g_strDefaultUsername = ""
  195. # If your data file uses spaces or a character other than comma as the
  196. # delimiter, you would also need to edit the g_strDelimiter value a few lines
  197. # below to indicate that fields are separated by spaces, rather than by commas.
  198. # For example:
  199. # g_strDelimiter = " "
  200. # Using a ";" might be a good alternative for a file that includes the comma
  201. # character as part of any legitimate session name or folder name, etc.
  202. global g_strDelimiter
  203. g_strDelimiter = "," # comma
  204. #g_strDelimiter = " " # space
  205. #g_strDelimiter = ";" # semi-colon
  206. #g_strDelimiter = chr(9) # tab
  207. #g_strDelimiter = "|||" # a more unique example of a delimiter.
  208. # The g_strSupportedFields indicates which of all the possible fields, are
  209. # supported in this example script. If a field designation is found in a data
  210. # file that is not listed in this variable, it will not be imported into the
  211. # session configuration.
  212. global g_strSupportedFields
  213. g_strSupportedFields = \
  214. "description,emulation,folder,hostname,port,protocol,session_name,username,logon_script"
  215. # If you wish to overwrite existing sessions, set the
  216. # g_bOverwriteExistingSessions to True; for this example script, we're playing
  217. # it safe and leaving any existing sessions in place :).
  218. global g_bOverwriteExistingSessions
  219. g_bOverwriteExistingSessions = False
  220. strHome = os.path.expanduser("~")
  221. global g_strMyDocs
  222. g_strMyDocs = strHome + "/Documents"
  223. g_strMyDesktop = strHome + "/Desktop"
  224. global g_strHostsFile
  225. g_strHostsFile = g_strMyDocs + "/MyDataFile.csv"
  226. global g_strExampleHostsFile
  227. g_strExampleHostsFile = \
  228. "\thostname,protocol,username,folder,emulation\n" + \
  229. "\t192.168.0.1,SSH2,root,Linux Machines,XTerm\n" + \
  230. "\t192.168.0.2,SSH2,root,Linux Machines,XTerm\n" + \
  231. "\t...\n" + \
  232. "\t10.0.100.1,SSH1,admin,CISCO Routers,VT100\n" + \
  233. "\t10.0.101.1,SSH1,admin,CISCO Routers,VT100\n" + \
  234. "\t...\n" + \
  235. "\tmyhost.domain.com,SSH2,administrator,Windows Servers,VShell\n" + \
  236. "\t...\n"
  237. g_strExampleHostsFile = g_strExampleHostsFile.replace(",", g_strDelimiter)
  238. global g_strConfigFolder, strFieldDesignations, g_vFieldsArray, vSessionInfo
  239. global strSessionName, strHostName, strPort
  240. global strUserName, strProtocol, strEmulation
  241. global strPathForSessions, g_strLine, nFieldIndex
  242. global strSessionFileName, strFolder, nDescriptionLineCount, strDescription
  243. global g_strLastError, g_strErrors, g_strSessionsCreated
  244. global g_nSessionsCreated, g_nDataLines, g_nCurLineNumber
  245. g_strLastError = ""
  246. g_strErrors = ""
  247. g_strSessionsCreated = ""
  248. g_nSessionsCreated = 0
  249. g_nDataLines = 0
  250. g_nCurLineNumber = 0
  251. global g_objReFolders, g_objReSession
  252. # Folders as specified in the data file can have
  253. # / chars since they can include sub-folder components
  254. g_objReFolders = re.compile(r'([\|\:\*\?\"\<\>])')
  255. # Session names, however, cannot have / chars
  256. g_objReSession = re.compile(r'([\|\:\*\?\"\<\>/])')
  257. global g_objReSpecialsFolders, g_objReSpecialsSession
  258. g_objReSpecialsFolders = re.compile(r'/(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])/', re.I)
  259. g_objReSpecialsSession = re.compile(r'^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])$', re.I)
  260. # Use current date/time info to avoid overwriting existing sessions by
  261. # importing sessions into a new folder named with a unique timestamp.
  262. g_strDateTimeTag = datetime.datetime.now().strftime("%Y%m%d_%H%M%S.%f")[:19]
  263. global g_bUseDefaultSessionOptions
  264. g_bUseDefaultSessionOptions = True
  265. global g_strBogusLinesNotImported
  266. g_strBogusLinesNotImported = ""
  267. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  268. def GetConfigPath():
  269. objConfig = crt.OpenSessionConfiguration("Default")
  270. # Try and get at where the configuration folder is located. To achieve
  271. # this goal, we'll use one of SecureCRT's cross-platform path
  272. # directives that means "THE path this instance of SecureCRT
  273. # is using to load/save its configuration": ${VDS_CONFIG_PATH}.
  274. # First, let's use a session setting that we know will do the
  275. # translation between the cross-platform moniker ${VDS_CONFIG_PATH}
  276. # and the actual value... say, "Upload Directory V2"
  277. strOptionName = "Upload Directory V2"
  278. # Stash the original value, so we can restore it later...
  279. strOrigValue = objConfig.GetOption(strOptionName)
  280. # Now set the value to our moniker...
  281. objConfig.SetOption(strOptionName, "${VDS_CONFIG_PATH}")
  282. # Make the change, so that the above templated name will get written
  283. # to the config...
  284. objConfig.Save()
  285. # Now, load a fresh copy of the config, and pull the option... so
  286. # that SecureCRT will convert from the template path value to the
  287. # actual path value:
  288. objConfig = crt.OpenSessionConfiguration("Default")
  289. strConfigPath = objConfig.GetOption(strOptionName)
  290. # Now, let's restore the setting to its original value
  291. objConfig.SetOption(strOptionName, strOrigValue)
  292. objConfig.Save()
  293. # Now return the config path
  294. return strConfigPath
  295. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  296. def ValidateFieldDesignations(strFields):
  297. global g_strDelimiter, g_strExampleHostsFile, g_strDefaultProtocol
  298. global g_vFieldsArray, g_strDefaultFolder, g_strDefaultUsername
  299. if strFields.find(g_strDelimiter) == -1:
  300. if len(g_strDelimiter) > 1:
  301. strDelimiterDisplay = g_strDelimiter
  302. else:
  303. if ord(g_strDelimiter) < 33 or ord(g_strDelimiter) > 126:
  304. strDelimiterDisplay = "ASCII[{0}]".format(ord(g_strDelimiter))
  305. else:
  306. strDelimiterDisplay = g_strDelimiter
  307. strDelim = crt.Dialog.Prompt(
  308. "Delimiter character [" + strDelimiterDisplay + "] was not found " +
  309. "in the header line of your data file.\r\n\r\n" +
  310. "What is the delimiter (field separator) that your file " +
  311. "is using?\r\n\r\n\t Enter \"NONE\" if your data file only has a single field.")
  312. if strDelim == "":
  313. MsgBox("Script cannot continue w/o a field delimiter.")
  314. return
  315. if strDelim != "NONE":
  316. g_strDelimiter = strDelim
  317. g_vFieldsArray = strFields.split(g_strDelimiter)
  318. if not "hostname" in [x.lower() for x in g_vFieldsArray]:
  319. strErrorMsg = "Invalid header line in data file. " + \
  320. "'hostname' field is required."
  321. if len(g_strDelimiter) > 1:
  322. strDelimiterDisplay = g_strDelimiter
  323. else:
  324. if ord(g_strDelimiter) < 33 or ord(g_strDelimiter) > 126:
  325. strDelimiterDisplay = "ASCII[{0}]".format(ord(g_strDelimiter))
  326. else:
  327. strDelimiterDisplay = g_strDelimiter
  328. MsgBox(strErrorMsg + "\n" +
  329. "The first line of the data file is a header line " +
  330. "that must include\n" +
  331. "a '" + strDelimiterDisplay +
  332. "' separated list of field keywords.\n" +
  333. "\n" +
  334. "'hostname' is a required keyword." +
  335. "\n\n" +
  336. "The remainder of the lines in the file should follow the " +
  337. "\n" +
  338. "pattern established by the header line " +
  339. "(first line in the file)." + "\n" + "For example:\n" +
  340. g_strExampleHostsFile,
  341. "Import Data To SecureCRT Sessions")
  342. return
  343. if not "protocol" in [x.lower() for x in g_vFieldsArray]:
  344. if strFields.lower().find("protocol=") == -1:
  345. # Load the default configuration and use that as the default
  346. # protocol.
  347. objConfig = crt.OpenSessionConfiguration("Default")
  348. g_strDefaultProtocol = objConfig.GetOption("Protocol Name")
  349. for strField in g_vFieldsArray:
  350. #MsgBox("{0}\nHas 'protocol': {1}\nHas '=': {2}".format(strField, strField.find("protocol"), strField.find("=")))
  351. if strField.lower().find("protocol") > -1 and \
  352. strField.lower().find("=") > -1:
  353. g_strDefaultProtocol = strField.split("=")[1].upper()
  354. #MsgBox(("Found a default protocol spec: {0}".format(g_strDefaultProtocol)))
  355. # Fix the protocol field since we know the default protocol
  356. # value
  357. strFields = strFields.replace(strField, "protocol")
  358. if strField.lower().find("folder") > -1 and \
  359. strField.lower().find("=") > -1:
  360. g_strDefaultFolder = strField.split("=")[1]
  361. strFields = strFields.replace(strField, "folder")
  362. if strField.lower().find("username") > -1 and \
  363. strField.lower().find("=") > -1:
  364. g_strDefaultUsername = strField.split("=")[1]
  365. strFields = strFields.replace(strField, "username")
  366. g_vFieldsArray = strFields.split(g_strDelimiter)
  367. return True
  368. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  369. def SessionExists(strSessionPath):
  370. # Returns True if a session specified as value for strSessionPath already
  371. # exists within the SecureCRT configuration.
  372. # Returns False otherwise.
  373. try:
  374. objTosserConfig = crt.OpenSessionConfiguration(strSessionPath)
  375. return True
  376. except Exception as objInst:
  377. return False
  378. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  379. def OpenPathInDefaultApp(strFile):
  380. strPlatform = sys.platform
  381. crt.Session.SetStatusText("Platform: {0}".format(strPlatform))
  382. crt.Sleep(200)
  383. try:
  384. if sys.platform.startswith('darwin'):
  385. subprocess.call(('open', strFile))
  386. elif strPlatform == "win32":
  387. os.startfile(strFile)
  388. elif sys.platform.startswith('linux'):
  389. subprocess.call(('xdg-open', strFile))
  390. else:
  391. MsgBox("Unknown operating system: " + os.name)
  392. except Exception, objErr:
  393. MsgBox(
  394. "Failed to open " + strFile + " with the default app.\n\n" +
  395. str(objErr).replace('\\\\', '\\').replace('u\'', '\''))
  396. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  397. def ValidateSessionFolderComponent(strComponent, strType):
  398. # strType can be either:
  399. # folder
  400. # session
  401. strOrigComponent = strComponent
  402. strType = strType.lower()
  403. global g_objReSession, g_objReFolders, g_strErrors
  404. global g_strBogusLinesNotImported
  405. # Check strComponent name for any invalid characters
  406. if strType == "folder":
  407. regexp = g_objReFolders
  408. else:
  409. regexp = g_objReSession
  410. objMatch = regexp.search(strComponent)
  411. if objMatch:
  412. strOffendingComponent = objMatch.group(1)
  413. if g_strErrors <> "":
  414. g_strErrors = "\r\n{0}".format(g_strErrors)
  415. g_strErrors = (
  416. "Error: Invalid character '{0}' ".format(strOffendingComponent) +
  417. "in {0} name \"{1}\" specified on line #{2:04d}".format(
  418. strType,
  419. strOrigComponent,
  420. g_nCurLineNumber) +
  421. ": {0}{1}".format(g_strLine, g_strErrors))
  422. g_strBogusLinesNotImported = "{0}\r\n{1}".format(
  423. g_strBogusLinesNotImported,
  424. g_strLine)
  425. return False
  426. # Now check for reserved names if we're on Windows
  427. if hasattr(sys, 'getwindowsversion'):
  428. global g_objReSpecialsFolders, g_objReSpecialsSession
  429. if strType == "folder":
  430. regexp = g_objReSpecialsFolders
  431. if strComponent[:1] <> "/":
  432. strComponent = "/{0}".format(strComponent)
  433. if strComponent[1:] <> "/":
  434. strComponent = "{0}/".format(strComponent)
  435. else:
  436. regexp = g_objReSpecialsSession
  437. objMatch = regexp.search(strComponent)
  438. if objMatch:
  439. strOffendingComponent = objMatch.group(1)
  440. if g_strErrors <> "":
  441. g_strErrors = "\r\n{0}".format(g_strErrors)
  442. g_strErrors = (
  443. "Error: Invalid {0} name ".format(strType) +
  444. "\"{0}\" specified on line #{1:04d}".format(
  445. strOrigComponent,
  446. g_nCurLineNumber) +
  447. ": {0} ---> '{1}' is a reserved name on Windows OS.{2}".format(
  448. g_strLine,
  449. strOffendingComponent,
  450. g_strErrors)
  451. )
  452. g_strBogusLinesNotImported = "{0}\r\n{1}".format(
  453. g_strBogusLinesNotImported,
  454. g_strLine
  455. )
  456. return False
  457. return True
  458. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  459. def Import():
  460. global g_strHostsFile, strFieldDesignations, g_strErrors, g_strDelimiter
  461. global g_strDefaultProtocol, g_nDataLines, g_strSessionsCreated, g_nSessionsCreated
  462. global g_strDefaultFolder, g_strDefaultUsername, g_strLine, g_nCurLineNumber
  463. global g_strBogusLinesNotImported, g_bUseDefaultSessionOptions
  464. g_strHostsFile = crt.Dialog.FileOpenDialog(
  465. "Please select the host data file to be imported.",
  466. "Open",
  467. g_strHostsFile,
  468. "CSV/Text Files (*.txt;*.csv)|*.txt;*.csv|All files (*.*)|*.*")
  469. if g_strHostsFile == "":
  470. return
  471. nReturn = crt.Dialog.MessageBox(
  472. "For new sessions created by this script...\r\n\r\n" +
  473. "Use settings from the \"Default\" session?\r\n" +
  474. "\tOr...\r\n" +
  475. "Use this script's customized options?\r\n" +
  476. " (see lines 836-880 in the script code for options & values)" +
  477. "\r\n" +
  478. "__________________________________________________\r\n" +
  479. "\r\n" +
  480. "Yes:\tUse \"Default\" Session options.\r\n" +
  481. "No:\tUse custom options defined in this script." +
  482. "\r\n" +
  483. "Cancel:\tExit script; let me read/modify the " +
  484. "code before I decide.",
  485. "Use \"Default\" Session options for imported sessions?",
  486. 3)
  487. if nReturn == 6: # Yes:
  488. g_bUseDefaultSessionOptions = True
  489. elif nReturn == 7: # No:
  490. g_bUseDefaultSessionOptions = False
  491. elif nReturn == 2: # Cancel:
  492. return
  493. nStartTime = time.time()
  494. bFoundHeader = False
  495. g_nCurLineNumber = 0
  496. vSessionInfo = []
  497. # Open our data file for reading
  498. with open(g_strHostsFile, "r") as objDataFile:
  499. # Iterate over each of the lines in the file, processing them one by one.
  500. for strLine in objDataFile:
  501. g_strLine = strLine.strip("\r\n")
  502. g_nCurLineNumber += 1
  503. # if g_nCurLineNumber == 1 or (g_nCurLineNumber % 10) == 0:
  504. crt.Session.SetStatusText(
  505. "Processing line #{0} from import file: {1}".format(
  506. g_nCurLineNumber, str(g_strLine)))
  507. bSaveSession = False
  508. strSessionPath = ""
  509. strPort = ""
  510. strProtocol = ""
  511. strHostName = ""
  512. strUserName = ""
  513. strEmulation = ""
  514. strFolder = ""
  515. strDescription = ""
  516. strLogonScript = ""
  517. if not bFoundHeader:
  518. strFieldDesignations = g_strLine
  519. # Validate the data file
  520. if not ValidateFieldDesignations(strFieldDesignations):
  521. return
  522. else:
  523. # Get a timer reading so that we can calculate how long it takes to import.
  524. nStartTime = time.time()
  525. bFoundHeader = True
  526. else:
  527. vSessionInfo = g_strLine.split(g_strDelimiter)
  528. if len(vSessionInfo) < len(g_vFieldsArray):
  529. if g_strLine.strip() == "":
  530. g_strLine = "[Empty Line]"
  531. g_strErrors = ("\n" +
  532. "Insufficient data on line #{0:04d}: ".format(g_nCurLineNumber) +
  533. "{1}{2}".format(g_nCurLineNumber, g_strLine, g_strErrors))
  534. elif len(vSessionInfo) > len(g_vFieldsArray):
  535. g_strErrors = g_strErrors + (
  536. "\n" +
  537. "==> Number of data fields on line #" +
  538. "{0:04d} ".format(g_nCurLineNumber) +
  539. "({0:d}) ".format(len(vSessionInfo)) +
  540. "does not match the number of fields in the " +
  541. "header ({0:d}).\r\n".format(
  542. len(g_vFieldsArray)) +
  543. " This line will not be imported " +
  544. "(Does the session name have a character " +
  545. "that matches the delimiter you're using?):" +
  546. "\r\n" +
  547. " " + g_strLine)
  548. g_strBogusLinesNotImported = (g_strBogusLinesNotImported +
  549. "\r\n" + g_strLine)
  550. bSaveSession = False
  551. else:
  552. # Variable used to determine if a session file should actually be
  553. # created, or if there was an unrecoverable error (and the session
  554. # should be skipped).
  555. bSaveSession = True
  556. # Now we will match the items from the new file array to the correct
  557. # variable for the session's ini file
  558. for nFieldIndex in xrange(0, len(vSessionInfo)):
  559. #MsgBox("nFieldIndex: {0}\nlen(vSessionInfo):{1}\n{2}:{3}".format(nFieldIndex, len(vSessionInfo), g_vFieldsArray[nFieldIndex], vSessionInfo[nFieldIndex]))
  560. strFieldLabel = g_vFieldsArray[nFieldIndex].strip().lower()
  561. if strFieldLabel == "session_name":
  562. strSessionName = vSessionInfo[nFieldIndex].strip()
  563. elif strFieldLabel == "logon_script":
  564. strLogonScript = vSessionInfo[nFieldIndex].strip()
  565. elif strFieldLabel == "port":
  566. strPort = vSessionInfo[nFieldIndex].strip()
  567. if not strPort == "":
  568. if not strPort.isdigit():
  569. bSaveSession = False
  570. g_strErrors = ("\nError: Invalid port \"{0}\" specified on line #{1:04d}: {2}{3}".format(
  571. strPort, g_nCurLineNumber, g_strLine, g_strErrors))
  572. elif strFieldLabel == "protocol":
  573. strProtocol = vSessionInfo[nFieldIndex].lower().strip()
  574. if strProtocol == "ssh2":
  575. strProtocol = "SSH2"
  576. elif strProtocol == "ssh1":
  577. strProtocol = "SSH1"
  578. elif strProtocol == "telnet":
  579. strProtocol = "Telnet"
  580. elif strProtocol == "serial" or strProtocol == "tapi":
  581. bSaveSession = False
  582. g_strErrors = ("\n" +
  583. "Error: Unsupported protocol \"" + vSessionInfo[nFieldIndex].strip() +
  584. "\" specified on line #" +
  585. "{0:04d}: {1}".format(g_nCurLineNumber, g_strLine) +
  586. g_strErrors)
  587. elif strProtocol == "rlogin":
  588. strProtocol = "RLogin"
  589. else:
  590. if g_strDefaultProtocol <> "":
  591. strProtocol = g_strDefaultProtocol
  592. else:
  593. bSaveSession = False
  594. g_strErrors = ("\n" +
  595. "Error: Invalid protocol \"" + strProtocol +
  596. "\" specified on line #" +
  597. "{0:04d}: {1}".format(g_nCurLineNumber, g_strLine) +
  598. g_strErrors)
  599. elif strFieldLabel == "hostname":
  600. strHostName = vSessionInfo[nFieldIndex].strip()
  601. if strHostName == "":
  602. bSaveSession = False
  603. g_strErrors = ("\n" +
  604. "Error: Hostname field on line #{0:04d} is empty: {1}".format(g_nCurLineNumber, g_strLine) +
  605. g_strErrors)
  606. elif strFieldLabel == "username":
  607. strUserName = vSessionInfo[nFieldIndex].strip()
  608. elif strFieldLabel == "emulation":
  609. strEmulation = vSessionInfo[nFieldIndex].lower().strip()
  610. if strEmulation == "xterm":
  611. strEmulation = "Xterm"
  612. elif strEmulation == "vt100":
  613. strEmulation = "VT100"
  614. elif strEmulation == "vt102":
  615. strEmulation = "VT102"
  616. elif strEmulation == "vt220":
  617. strEmulation = "VT220"
  618. elif strEmulation == "ansi":
  619. strEmulation = "ANSI"
  620. elif strEmulation == "linux":
  621. strEmulation = "Linux"
  622. elif strEmulation == "scoansi":
  623. strEmulation = "SCOANSI"
  624. elif strEmulation == "vshell":
  625. strEmulation = "VShell"
  626. elif strEmulation == "wyse50":
  627. strEmulation = "WYSE50"
  628. elif strEmulation == "wyse60":
  629. strEmulation = "WYSE60"
  630. else:
  631. bSaveSession = False
  632. g_strErrors = ("\n" +
  633. "Error: Invalid emulation \"{0}\" specified on line #{1:04d}: {2}{3}".format(
  634. strEmulation, g_nCurLineNumber, g_strLine, g_strErrors))
  635. elif strFieldLabel == "folder":
  636. strFolderOrig = vSessionInfo[nFieldIndex].strip()
  637. strFolder = strFolderOrig.lower()
  638. if strFolder == "":
  639. strFolder = g_strDefaultFolder
  640. strFolderOrig = g_strDefaultFolder
  641. elif strFieldLabel == "description":
  642. strCurDescription = vSessionInfo[nFieldIndex].strip()
  643. if strDescription == "":
  644. strDescription = strCurDescription
  645. else:
  646. strDescription = "{0}\\r{1}".format(strDescription, strCurDescription)
  647. strDescription = strDescription.replace("\\r", "\r")
  648. else:
  649. # If there is an entry that the script is not set to use
  650. # in strFieldDesignations, stop the script and display a
  651. # message
  652. strMsg1 = (
  653. "Error: Unknown field designation: {0}\n".format(
  654. g_vFieldsArray[nFieldIndex]) +
  655. "\tSupported fields are as follows:\n\n\t" +
  656. "{0}\n\n".format(g_strSupportedFields) +
  657. "For a description of the supported fields, " +
  658. "see the comments in the sample script file." +
  659. "")
  660. if g_strErrors.strip() <> "":
  661. strMsg1 = (strMsg1 + "\n\n" +
  662. "Other errors found so far include: " +
  663. g_strErrors)
  664. MsgBox(strMsg1, "Import Data To SecureCRT Sessions: Data File Error")
  665. return
  666. # Use hostname if a session_name field wasn't present
  667. if strSessionName == "":
  668. strSessionName = strHostName
  669. if not ValidateSessionFolderComponent(strSessionName, "session"):
  670. bSaveSession = False
  671. if strFolderOrig == "":
  672. strFolderOrig = g_strDefaultFolder
  673. if not ValidateSessionFolderComponent(strFolderOrig, "folder"):
  674. bSaveSession = False
  675. if bSaveSession:
  676. # Canonicalize the path to the session, as needed
  677. strSessionPath = strSessionName
  678. if strFolderOrig.strip() <> "":
  679. if strFolderOrig[1:] <> "/":
  680. strSessionPath = "{0}/{1}".format(strFolderOrig, strSessionName)
  681. else:
  682. strSessionPath = "{0}/{1}".format(strFolderOrig, strSessionName)
  683. if strUserName.strip() == "":
  684. strUserName = g_strDefaultUsername
  685. # Strip any leading '/' characters from the session path
  686. strSessionPath = strSessionPath.lstrip('/')
  687. if SessionExists(strSessionPath):
  688. if not g_bOverwriteExistingSessions:
  689. # Append a unique tag to the session name, if it already exists
  690. strSessionPath = "{0}(import_({1})".format(strSessionPath, datetime.datetime.now().strftime("%Y%m%d_%H%M%S.%f")[:19])
  691. #MsgBox(
  692. # "Line #{0}: {1}\nbSaveSession: {2}\nSessionPath: {3}\n\nPort: {4}\nProtocol: {5}\nHostname: {6}\nUsername: {7}\nEmulation: {8}\nFolder: {9}\nDescription: {10}\n\n{11}".format(
  693. # g_nCurLineNumber, g_strLine, bSaveSession, strSessionPath, strPort, strProtocol, strHostName, strUserName, strEmulation, strFolder, strDescription, g_strErrors))
  694. # Now: Create the session.
  695. # ===================================================================
  696. # Copy the default session settings into new session name and set the
  697. # protocol. Setting protocol protocol is essential since some variables
  698. # within a config are only available with certain protocols. For example,
  699. # a telnet configuration will not be allowed to set any port forwarding
  700. # settings since port forwarding settings are specific to SSH.
  701. objConfig = crt.OpenSessionConfiguration("Default")
  702. if strProtocol == "":
  703. strProtocol = g_strDefaultProtocol
  704. objConfig.SetOption("Protocol Name", strProtocol)
  705. # We opened a default session & changed the protocol, now we save the
  706. # config to the new session path:
  707. objConfig.Save(strSessionPath)
  708. # Now, let's open the new session configuration we've saved, and set
  709. # up the various parameters that were specified in the file.
  710. objConfig = crt.OpenSessionConfiguration(strSessionPath)
  711. if objConfig.GetOption("Protocol Name") != strProtocol:
  712. MsgBox("Error: Protocol not set. Expected \"{0}\", but got \"{1}\"".format(strProtocol, objConfig.GetOption("Protocol Name")))
  713. return
  714. if strDescription != "":
  715. vDescription = strDescription.split("\r")
  716. objConfig.SetOption("Description", vDescription)
  717. if strLogonScript != "":
  718. objConfig.SetOption("Script Filename V2", strLogonScript)
  719. objConfig.SetOption("Use Script File", True)
  720. objConfig.SetOption("Emulation", strEmulation)
  721. if strProtocol.lower() <> "serial":
  722. if strHostName != "":
  723. objConfig.SetOption("Hostname", strHostName)
  724. if strUserName != "":
  725. objConfig.SetOption("Username", strUserName)
  726. if strProtocol.upper() == "SSH2":
  727. if strPort == "":
  728. strPort = 22
  729. objConfig.SetOption("[SSH2] Port", int(strPort))
  730. elif strProtocol.upper() == "SSH1":
  731. if strPort == "":
  732. strPort = "22"
  733. objConfig.SetOption("[SSH1] Port", int(strPort))
  734. elif strProtocol.upper() == "TELNET":
  735. if strPort == "":
  736. strPort = "23"
  737. objConfig.SetOption("Port", int(strPort))
  738. try:
  739. # Only enter this next block if the individual decided to
  740. # use this script's settings, not "Default" session's values.
  741. if not g_bUseDefaultSessionOptions:
  742. # If you don't want ANSI Color enabled for all imported sessions (regardless
  743. # of value in Default session, comment out the following line)
  744. # ---------------------------------------------------------------------------
  745. objConfig.SetOption("ANSI Color", True)
  746. objConfig.SetOption("Color Scheme", "Solarized Darcula") # Requires 8.3 or newer
  747. objConfig.SetOption("Color Scheme Overrides Ansi Color", True)
  748. # Additional "SetOption" calls desired here... Comment out those you don't
  749. # want, un-comment those you do want, and add more lines for other options
  750. # you desire to be set by default for all sessions created from the import
  751. # operation. Note: ${VDS_USER_DATA_PATH} = a cross-platform representation
  752. # of the current user's "Documents" folder.
  753. # ---------------------------------------------------------------------------
  754. objConfig.SetOption("Auto Reconnect", True)
  755. # If you desire templated log file naming to be enabled
  756. # for all imported sessions, uncommment the following 3
  757. # lines of code:
  758. # objDefaultConfig = crt.OpenSessionConfiguration("Default")
  759. # if objDefaultConfig.GetOption("Log Filename V2") == "":
  760. # objConfig.SetOption("Log Filename V2", "${VDS_USER_DATA_PATH}\_ScrtLog(%S)_%Y%M%D_%h%m%s.%t.txt")
  761. objConfig.SetOption("Start Log Upon Connect", False)
  762. objConfig.SetOption("Rows", 60)
  763. objConfig.SetOption("Cols", 140)
  764. objConfig.SetOption("Use Word Delimiter Chars", True)
  765. if str(objConfig.GetOption("Word Delimiter Chars")) == "":
  766. objConfig.SetOption("Word Delimiter Chars", " <>()+=$%!#*")
  767. if int(objConfig.GetOption("Scrollback")) == 500:
  768. objConfig.SetOption("Scrollback", 12345)
  769. # objConfig.SetOption("Keyword Set", "MyCiscoKeywords")
  770. # objConfig.SetOption("Highlight Color", True)
  771. # objConfig.SetOption("Highlight Reverse Video", True)
  772. # objConfig.SetOption("Firewall Name", "GlobalOptionDefinedFirewallName")
  773. # objConfig.SetOption("Ignore Window Title Change Requests", True)
  774. objConfig.SetOption("Key Exchange Algorithms", "diffie-hellman-group-exchange-sha256,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1")
  775. objConfig.SetOption("Idle NO-OP Check", True)
  776. objConfig.SetOption("Idle NO-OP Timeout", 60)
  777. # objConfig.SetOption("SSH2 Authentications V2", "publickey,keyboard-interactive,password")
  778. # objConfig.SetOption("Identity Filename V2", "${VDS_USER_DATA_PATH}\Identity")
  779. # objConfig.SetOption("Firewall Name", "Session:JumpHost")
  780. objConfig.SetOption("Auth Prompts in Window", True)
  781. except Exception, objInst:
  782. MsgBox("failure detected:\n\t{0}".format(str(objInst)))
  783. objConfig.Save()
  784. if g_strSessionsCreated <> "":
  785. g_strSessionsCreated = g_strSessionsCreated + "\n"
  786. g_strSessionsCreated = g_strSessionsCreated + " " + strSessionPath
  787. g_nSessionsCreated += 1
  788. # Reset all variables in preparation for reading in the next line of
  789. # the hosts info file.
  790. strEmulation = ""
  791. strPort = ""
  792. strHostName = ""
  793. strFolder = ""
  794. strUserName = ""
  795. strSessionName = ""
  796. strDescription = ""
  797. nDescriptionLineCount = 0
  798. g_nDataLines += 1
  799. nTimeElapsed = time.time() - nStartTime
  800. strResults = "Import operation completed in %2.3f seconds." % (nTimeElapsed)
  801. if g_nSessionsCreated > 0:
  802. strResults = (strResults + "\r\n" +
  803. "-" * 70 + "\r\n" +
  804. "Number of Sessions created: %d\r\n" % (g_nSessionsCreated))
  805. strResults = strResults + "\r\n" + g_strSessionsCreated
  806. else:
  807. strResults = (strResults + "\r\n" +
  808. "-" * 70 + "\r\n" +
  809. "No sessions were created from %d lines of data." % (g_nDataLines))
  810. crt.Session.SetStatusText("Import operation completed in {0:2.3f} seconds".format(nTimeElapsed))
  811. # Log activity information to a file for debugging purposes...
  812. strFilename = "{0}/__SecureCRT-Session-ImportLog-{1}.txt".format(g_strMyDocs, g_strDateTimeTag)
  813. if g_strErrors == "":
  814. strResults = (
  815. "No errors/warnings encountered from the import operation.\r\n\r\n{0}".format(strResults))
  816. else:
  817. strResults = "Errors/warnings from this operation include: \r\n{0}\r\n{1}\r\n{2}\r\n\r\n".format(
  818. g_strErrors, "-" * 70, strResults)
  819. if g_strBogusLinesNotImported <> "":
  820. strResults = (
  821. "The following lines from the data file were *not* imported for " +
  822. "various reasons detailed below:\r\n" +
  823. "=" * 70 + "\r\n" +
  824. strFieldDesignations +
  825. g_strBogusLinesNotImported + "\r\n" +
  826. "-" * 70 + "\r\n" +
  827. "Fix the above lines to resolve the issues and save " +
  828. "the fixed lines to a new file. You can then run this " +
  829. "script again to import these skipped sessions.\r\n\r\n" +
  830. strResults)
  831. cFilenames = [
  832. "{0}/__SecureCRT-Session-ImportLog-{1}.txt".format(g_strMyDocs, g_strDateTimeTag).replace("\\", "/"),
  833. "{0}/__SecureCRT-Session-ImportLog-{1}.txt".format(g_strMyDesktop, g_strDateTimeTag).replace("\\", "/"),
  834. "{0}/__SecureCRT-Session-ImportLog-{1}.txt".format(GetConfigPath(), g_strDateTimeTag).replace("\\", "/")
  835. ]
  836. bSuccess = False
  837. for strFilename in cFilenames:
  838. try:
  839. objFile = open(strFilename, "w")
  840. bSuccess = True
  841. except:
  842. crt.Session.SetStatusText("Unable to open results file.")
  843. strResults = (strResults + "\n" +
  844. "Failed to write summary results to: {0}".format(strFilename))
  845. if not os.path.isfile(strFilename):
  846. bSuccess = False
  847. else:
  848. break
  849. if not bSuccess:
  850. if ":\\" in g_strMyDocs:
  851. strResults = strResults.replace("\n", "\r\n")
  852. crt.Clipboard.Text = strResults
  853. MsgBox(
  854. "Attempted to write summary results to the file locations below, " +
  855. "but access was denied.\r\n\t{0}".format("\r\n\t".join(cFilenames)) +
  856. "\r\n\r\nResults are in the clipboard. " +
  857. "Paste them into your favorite app now to see what occurred.")
  858. return
  859. objFile.write(strResults)
  860. objFile.close()
  861. # Display the log file as an indication that the information has been
  862. # imported.
  863. OpenPathInDefaultApp(strFilename)
  864. crt.Session.SetStatusText("")
  865. Import()

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/963450
推荐阅读
相关标签
  

闽ICP备14008679号