├── LICENSE ├── Notice.txt ├── README.md ├── bin ├── batch_run.py └── batch_run_gui.py ├── common ├── __init__.py ├── common.py ├── common_lsf.py ├── common_pyqt5.py └── common_secure.so ├── config └── host.list ├── data ├── demo │ ├── command_line_run_demo.gif │ ├── gui_info_demo.gif │ └── gui_run_demo.gif └── pictures │ ├── G.png │ ├── H.png │ ├── N.png │ ├── Z.png │ ├── about.png │ ├── cancel.png │ ├── close.png │ ├── database.png │ ├── exit.png │ ├── fail.png │ ├── gun.png │ ├── load.png │ ├── log.png │ ├── magnifier.png │ ├── monitor.ico │ ├── open.png │ ├── pend.png │ ├── radar.png │ ├── save.png │ ├── select.png │ ├── slow.png │ ├── switch.png │ ├── trace.png │ └── version.png ├── db ├── host_asset │ └── .gitignore ├── host_info │ └── .gitignore ├── host_queue │ └── .gitignore ├── host_stat │ └── .gitignore └── network_scan │ └── .gitignore ├── docs └── batchRun_user_manual.pdf ├── install.py ├── requirements.txt ├── scripts ├── .gitignore ├── cleanup │ ├── clean_tmp.sh │ └── drop_caches.sh └── ssh │ └── nopassword_ssh.sh └── tools ├── encrypt_python.py ├── message.py ├── network_scan.py ├── patch.py ├── sample_host_info.py ├── sample_host_queue.py ├── sample_host_stat.py ├── save_password.py ├── show_top_file.py └── switch_etc_hosts.py /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Notice.txt: -------------------------------------------------------------------------------- 1 | Copyright (year) Bytedance Ltd. and/or its affiliates 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **Version:** V2.2 2 | 3 | 4 | ## What's batchRun? 5 | batchRun is a batch opration, asset management, and information collection tool applied to HPC systems. 6 | You can run batchRun with command line or GUI mode. 7 | 8 | 9 | ## Python dependency 10 | Need python3.12.7 11 | Install python library dependency with command 12 | 13 | pip install -r requirements.txt 14 | 15 | 16 | ## Install 17 | Copy install package into install directory. 18 | Execute below command under install directory. 19 | 20 | python3 install.py 21 | 22 | 23 | ## Quick start 24 | Execute command `batch_run --help` to get usage information. 25 | Execute command `batch_run --gui` to enable GUI mode. 26 | * Below is a demo on how to run command with command line. 27 | 28 | ![command_line_run_demo](data/demo/command_line_run_demo.gif) 29 | 30 | * Below is a demo on how to run command with GUI. 31 | 32 | ![gui_run_demo](data/demo/gui_run_demo.gif) 33 | 34 | * Below is a demo on how to view host info with GUI. 35 | 36 | ![host_filter_demo](data/demo/gui_info_demo.gif) 37 | 38 | 39 | ## Configuration 40 | Come into /config directory, 41 | 42 | - Update "config.py" for batchRun basic configuration. 43 | - Update "host.list" for group-host relationship. 44 | - Update "password.encrypted" for encrypted user/password information if necessary. 45 | 46 | 47 | ## Sample 48 | Collect host information with tool "sample_host_info". 49 | 50 | 51 | ## Doc 52 | More details please see ["docs/batchRun_user_manual.pdf"](./docs/batchRun_user_manual.pdf) 53 | 54 | 55 | ## Update history 56 | *** 57 | | Version | Date | Update content | 58 | |:--------|:----------|:-------------------------------------------| 59 | | V1.0 | (2022.12) | Release original version. | 60 | | V1.1 | (2023.07) | Support host_ip & host_name multi-mapping. | 61 | | | | Remove LSF supporting. | 62 | | V1.2 | (2024.08) | Add host info sampling function. | 63 | | V2.0 | (2024.10) | Add GUI with GROUP/HOST/RUN/LOG tabs. | 64 | | V2.1 | (2025.01) | Add SCAN tab on GUI. | 65 | | | | Add STAT tab on GUI. | 66 | | | | Add scheduler/cluster/queue on GROUP tab. | 67 | | | | Fix the id authentication bug on crontab. | 68 | | V2.2 | (2025.02) | Merge GROUP&HOST tabs on GUI. | 69 | | | | Add ASSET tab on GUI. | 70 | -------------------------------------------------------------------------------- /bin/batch_run.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ################################ 3 | # File Name : batch_run.py 4 | # Author : liyanqing.1987 5 | # Created On : 2021-08-09 19:18:43 6 | # Description : batchRun is a batch opration, asset management, and information 7 | # collection tool applied to HPC systems. 8 | ################################ 9 | import os 10 | import re 11 | import sys 12 | import json 13 | import time 14 | import copy 15 | import shutil 16 | import getpass 17 | import datetime 18 | import argparse 19 | import threading 20 | 21 | sys.path.append(str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/config') 22 | import config 23 | 24 | sys.path.append(str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/common') 25 | import common 26 | import common_secure 27 | 28 | os.environ['PYTHONUNBUFFERED'] = '1' 29 | VERSION = 'V2.2' 30 | VERSION_DATE = '2025.02.25' 31 | START_TIME = datetime.datetime.now().strftime('%Y%m%d_%H%M%S') 32 | CURRENT_USER = getpass.getuser() 33 | LOGIN_USER = common.get_login_user() 34 | 35 | 36 | def read_args(): 37 | """ 38 | Read in arguments. 39 | """ 40 | parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) 41 | 42 | parser.add_argument('-H', '--hosts', 43 | nargs='+', 44 | default=[], 45 | help='''Specify host(s) with below format: 46 | 47 | 48 | : 49 | 50 | : 51 | ~ 52 | ~ 53 | 54 | "all | ALL" means all hosts on ''' + str(config.host_list) + '''. 55 | "~" means exclud specified host.''') 56 | parser.add_argument('-G', '--groups', 57 | nargs='+', 58 | default=[], 59 | help='''Specify host group(s) with below format: 60 | 61 | 62 | ~ 63 | 64 | "all | ALL" means all groups on ''' + str(config.host_list) + '''. 65 | "~" means exclud specified group.''') 66 | parser.add_argument('-L', '--list', 67 | action='store_true', 68 | default=False, 69 | help='List specified host(s)/group(s).') 70 | parser.add_argument('-u', '--user', 71 | default=CURRENT_USER, 72 | help='Specify the user identity for SSH login to specified host.') 73 | parser.add_argument('-p', '--password', 74 | default='', 75 | help='Specify the user password for SSH login to specified host.') 76 | parser.add_argument('-c', '--command', 77 | nargs='+', 78 | default=[], 79 | help='Specify the command to run on specified remote host(s).') 80 | parser.add_argument('-P', '--parallel', 81 | type=int, 82 | default=1, 83 | help='''Specify the parallelism of command execution with a number, default is "1" (serial mode). 84 | "0" : Parallel mode, run all tasks in parallel; 85 | "1" : Serial mode; 86 | "n" : Parallel mode, run n tasks in parallel.''') 87 | parser.add_argument('-t', '--timeout', 88 | type=int, 89 | help='Specify the timeout for SSH, which defaults to ' + str(config.serial_timeout) + ' seconds in serial and ' + str(config.parallel_timeout) + ' seconds in parallel.') 90 | parser.add_argument('-l', '--output_message_level', 91 | type=int, 92 | choices=[0, 1, 2, 3, 4], 93 | default=3, 94 | help='''Specify output message level, which defaults to "3" in serial and "0" in parallel. 95 | "0" : print host info; 96 | "1" : print command output message; 97 | "2" : print host info and the first line of the command output message; 98 | "3" : print host info and complete command output message; 99 | "4" : print verbose information with ssh command.''') 100 | parser.add_argument('-o', '--output_file', 101 | default='', 102 | help='Export output message of command to specified file instead of on the screen.') 103 | parser.add_argument('-g', '--gui', 104 | action='store_true', 105 | default=False, 106 | help='Open batchRun with GUI format.') 107 | parser.add_argument('-v', '--version', 108 | action="store_true", 109 | default=False, 110 | help='Show batchRun version information.') 111 | 112 | args = parser.parse_args() 113 | 114 | # Enable GUI mode. 115 | if args.gui: 116 | os.system(str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/bin/batch_run_gui') 117 | sys.exit(0) 118 | 119 | # Get batchRun version information. 120 | if args.version: 121 | common.bprint('Version : ' + str(VERSION)) 122 | common.bprint('Release : ' + str(VERSION_DATE)) 123 | sys.exit(0) 124 | 125 | # Check hosts/groups settings. 126 | if (not args.hosts) and (not args.groups): 127 | common.bprint('Neither of argument "--hosts" or "--groups" is specified.', level='Error') 128 | sys.exit(1) 129 | 130 | # Analyze host file. 131 | if (len(args.hosts) == 1) and os.path.isfile(args.hosts[0]): 132 | with open(args.hosts[0], 'r') as HF: 133 | args.hosts = [] 134 | 135 | for line in HF.readlines(): 136 | if (not re.match(r'^\s*#.*$', line)) and (not re.match(r'^\s*$', line)): 137 | args.hosts.append(line.strip()) 138 | 139 | # Analyze group file. 140 | if (len(args.groups) == 1) and os.path.isfile(args.groups[0]): 141 | with open(args.groups[0], 'r') as GF: 142 | args.groups = [] 143 | 144 | for line in GF.readlines(): 145 | if (not re.match(r'^\s*#.*$', line)) and (not re.match(r'^\s*$', line)): 146 | args.groups.append(line.strip()) 147 | 148 | # Get specified host(s) info. 149 | host_list_class = common.ParseHostList() 150 | (specified_host_dic, expected_group_list, excluded_group_list) = get_specified_hosts(host_list_class, args.hosts, args.groups) 151 | 152 | if not specified_host_dic: 153 | common.bprint('No valid host is specified.', level='Error') 154 | sys.exit(1) 155 | 156 | # List hosts. 157 | if args.list: 158 | list_hosts(host_list_class, specified_host_dic, expected_group_list, excluded_group_list, args.output_file) 159 | sys.exit(0) 160 | 161 | # Check command setting. 162 | if not args.command: 163 | common.bprint('No command is specified.', level='Error') 164 | sys.exit(1) 165 | else: 166 | # Try to find command under batchRun scripts directory. 167 | scripts_dir = str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/scripts' 168 | command_name = args.command[0] 169 | 170 | for root, dirs, files in os.walk(scripts_dir): 171 | if command_name in files: 172 | args.command[0] = os.path.join(root, command_name) 173 | 174 | # Filter illegal command. 175 | format_command = ' '.join(args.command) 176 | format_command = re.sub(r'\\', '', format_command) 177 | 178 | for illegal_command in config.illegal_command_list: 179 | if (format_command in config.illegal_command_list) or re.match(r'^' + str(illegal_command) + '$', format_command): 180 | common.bprint('Illegal command!', level='Error') 181 | sys.exit(1) 182 | 183 | # Reset default timeout setting. 184 | if not args.timeout: 185 | if args.parallel == 1: 186 | args.timeout = config.serial_timeout 187 | else: 188 | args.timeout = config.parallel_timeout 189 | 190 | # Set output_message_level for parallel mode. 191 | if (args.parallel != 1) and (not args.output_file) and (args.output_message_level in [3, 4]): 192 | common.bprint('Switch output_message_level to "0" on parallel mode.', level='Warning') 193 | args.output_message_level = 0 194 | 195 | return specified_host_dic, args.user, args.password, args.command, args.parallel, args.timeout, args.output_message_level, args.output_file 196 | 197 | 198 | def get_specified_hosts(host_list_class, specified_host_list, specified_group_list): 199 | """ 200 | specified_host_dic = {: {'host_name': [,], 'ssh_port': , 'groups': [,]}} 201 | or 202 | specified_host_dic = {: {'host_ip': [,], 'ssh_port': [,], 'groups': [[,],]}} 203 | or 204 | specified_host_dic = {: {'ssh_port': }} 205 | """ 206 | specified_host_dic = {} 207 | excluded_host_list = [] 208 | expected_group_list = [] 209 | excluded_group_list = [] 210 | 211 | if specified_host_list or specified_group_list: 212 | # If groups are specified, parse and save. 213 | if specified_group_list: 214 | (specified_host_dic, excluded_host_list, expected_group_list, excluded_group_list) = common.parse_specified_groups(specified_group_list, host_list_class, specified_host_dic, excluded_host_list, expected_group_list, excluded_group_list) 215 | 216 | # If hosts are specified, parse and save. 217 | if specified_host_list: 218 | (specified_host_dic, excluded_host_list, expected_group_list, excluded_group_list) = common.parse_specified_hosts(specified_host_list, host_list_class, specified_host_dic, excluded_host_list, expected_group_list, excluded_group_list) 219 | 220 | return specified_host_dic, expected_group_list, excluded_group_list 221 | 222 | 223 | def list_hosts(host_list_class, specified_host_dic, expected_group_list, excluded_group_list, output_file): 224 | """ 225 | List specified hosts. 226 | """ 227 | if output_file: 228 | with open(output_file, 'w') as OF: 229 | OF.write(str(json.dumps(specified_host_dic, ensure_ascii=False, indent=4)) + '\n') 230 | common.bprint('* Host(s) info has been saved into "' + str(output_file) + '".') 231 | else: 232 | remaining_host_list = list(specified_host_dic.keys()) 233 | 234 | for (group, group_dic) in host_list_class.host_list_dic.items(): 235 | if (group not in excluded_group_list) and (group in expected_group_list): 236 | print('GROUP : [' + str(group) + ']') 237 | 238 | # Show hosts info. 239 | if 'hosts' in group_dic: 240 | for host_ip in group_dic['hosts'].keys(): 241 | if 'host_name' in group_dic['hosts'][host_ip]: 242 | host_name_list = group_dic['hosts'][host_ip]['host_name'] 243 | else: 244 | host_name_list = ['',] 245 | 246 | if 'ssh_port' in group_dic['hosts'][host_ip]: 247 | ssh_port = group_dic['hosts'][host_ip]['ssh_port'] 248 | else: 249 | ssh_port = '' 250 | 251 | for host_name in host_name_list: 252 | if (host_ip in specified_host_dic) or (host_name in specified_host_dic): 253 | print(' %-15s %s %s' % (host_ip, host_name, ssh_port)) 254 | 255 | if (host_ip in specified_host_dic) and (host_ip in remaining_host_list): 256 | remaining_host_list.remove(host_ip) 257 | elif (host_name in specified_host_dic) and (host_name in remaining_host_list): 258 | remaining_host_list.remove(host_name) 259 | 260 | # Show sub_groups info. 261 | if 'sub_groups' in group_dic: 262 | for sub_group in group_dic['sub_groups']: 263 | print(' ' + str(sub_group) + '/') 264 | 265 | # Show exclude_hosts info. 266 | if 'exclude_hosts' in group_dic: 267 | if 'host_ip' in group_dic['exclude_hosts']: 268 | for host_ip in group_dic['exclude_hosts']['host_ip']: 269 | print(' ~%s' % (host_ip)) 270 | 271 | if 'host_name' in group_dic['exclude_hosts']: 272 | for host_name in group_dic['exclude_hosts']['host_name']: 273 | print(' ~%s' % (host_name)) 274 | 275 | # Show execlude_groups info. 276 | if 'exclude_groups' in group_dic: 277 | for exclude_group in group_dic['exclude_groups']: 278 | print(' ~' + str(exclude_group) + '/') 279 | 280 | if remaining_host_list: 281 | print('UNRECOGNIZED HOST :') 282 | 283 | for host in remaining_host_list: 284 | print(' ' + str(host)) 285 | 286 | 287 | class BatchRun(): 288 | def __init__(self, specified_host_dic, user, password, command_list, parallel, timeout, output_message_level, output_file): 289 | self.specified_host_dic = specified_host_dic 290 | self.user = user 291 | self.password = password 292 | self.command_list = self.preprocess_command_string(command_list) 293 | self.parallel = parallel 294 | self.timeout = timeout 295 | self.output_message_level = output_message_level 296 | self.output_file = output_file 297 | 298 | # Below self.command_missing_compile_list is only for bash/csh/tcsh. 299 | self.command_missing_compile_list = [re.compile(r'^bash:\s+(\S+):\s+command not found...\s*$'), re.compile(r'^bash:\s+(\S+):\s+No such file or directory\s*$'), re.compile(r'^(\S+):\s+Command not found.$')] 300 | self.timeout_string_list = ['Timeout exceeded', 'pexpect.exceptions.TIMEOUT'] 301 | 302 | self.password_host_list = self.get_password_hosts() 303 | 304 | def preprocess_command_string(self, command_list): 305 | """ 306 | Remove unreasonable escape for "-". 307 | """ 308 | new_command_list = [] 309 | 310 | for command_string in command_list: 311 | if re.search(r'\\-', command_string): 312 | command_string = re.sub(r'\\-', '-', command_string) 313 | 314 | new_command_list.append(command_string) 315 | 316 | return new_command_list 317 | 318 | def save_command(self): 319 | """ 320 | Save command info into command history file under config.db_path/log. 321 | """ 322 | if hasattr(config, 'db_path') and config.db_path: 323 | # Create log dir. 324 | log_dir = str(config.db_path) + '/log' 325 | common.create_dir(log_dir, permission=0o1777) 326 | log_user_dir = str(log_dir) + '/' + str(CURRENT_USER) 327 | common.create_dir(log_user_dir, permission=0o700) 328 | 329 | # Write command history file. 330 | command_history_file = str(log_user_dir) + '/command.his' 331 | log_file = str(log_user_dir) + '/' + str(START_TIME) 332 | 333 | try: 334 | with open(command_history_file, 'a') as CHF: 335 | start_date = START_TIME.split('_')[0] 336 | start_time = START_TIME.split('_')[1] 337 | cmd_string = ' '.join(sys.argv).strip() 338 | command_dic = {'date': start_date, 'time': start_time, 'user': CURRENT_USER, 'login_user': LOGIN_USER, 'command': cmd_string, 'log': log_file} 339 | CHF.write(str(json.dumps(command_dic, ensure_ascii=False)) + '\n') 340 | except Exception as warning: 341 | common.bprint(f'Failed on opening "{command_history_file}" for read, {warning}', level='Warning') 342 | 343 | def save_log(self, message, end='\n'): 344 | """ 345 | Save output message into log file under config.db_path/log. 346 | """ 347 | if hasattr(config, 'db_path') and config.db_path: 348 | # Write log file. 349 | log_file = str(config.db_path) + '/log/' + str(CURRENT_USER) + '/' + str(START_TIME) 350 | 351 | try: 352 | with open(log_file, 'a') as LF: 353 | LF.write(str(message) + str(end)) 354 | except Exception as warning: 355 | common.bprint(f'Failed on opening "{log_file}" for read, {warning}', level='Warning') 356 | 357 | def save_out(self, message, end='\n', host=''): 358 | """ 359 | Print output message on screen, or save output message into output file. 360 | """ 361 | if self.output_file: 362 | # Update output_file with "HOST". 363 | output_file = self.output_file 364 | 365 | if host: 366 | output_file = re.sub('HOST', host, output_file) 367 | 368 | # Create output_dir if not exists. 369 | output_dir = os.path.dirname(output_file) 370 | 371 | if output_dir and (not os.path.exists(output_dir)): 372 | common.create_dir(output_dir, permission=0o777) 373 | 374 | # Write output file. 375 | with open(output_file, 'a') as OF: 376 | OF.write(str(message) + str(end)) 377 | else: 378 | print(message, end=end) 379 | 380 | def get_password_hosts(self): 381 | """ 382 | Get all specified host(s) from user password file. 383 | """ 384 | password_host_list = [] 385 | password_file = str(config.db_path) + '/password/' + str(self.user) 386 | 387 | if os.path.exists(password_file): 388 | try: 389 | with open(password_file, 'r') as PF: 390 | for line in PF.readlines(): 391 | host_name = line.split()[1] 392 | 393 | if host_name != 'default': 394 | password_host_list.append(host_name) 395 | except Exception as warning: 396 | common.bprint(f'Failed on opening "{password_file}" for read, {warning}', level='Warning') 397 | 398 | return password_host_list 399 | 400 | def get_ssh_command(self, host, host_ip, ssh_port, command_list): 401 | """ 402 | Get full ssh command based on host & ssh_port. 403 | """ 404 | # Default ssh setting. 405 | if config.default_ssh_command: 406 | ssh_command = config.default_ssh_command 407 | else: 408 | ssh_command = 'ssh -o StrictHostKeyChecking=no -t -q' 409 | 410 | if ssh_port: 411 | ssh_command = str(ssh_command) + ' -p ' + str(ssh_port) 412 | 413 | # Add user setting. 414 | if self.user: 415 | if host_ip: 416 | ssh_command = str(ssh_command) + ' ' + str(self.user) + '@' + str(host_ip) 417 | else: 418 | ssh_command = str(ssh_command) + ' ' + str(self.user) + '@' + str(host) 419 | else: 420 | if host_ip: 421 | ssh_command = str(ssh_command) + ' ' + str(host_ip) 422 | else: 423 | ssh_command = str(ssh_command) + ' ' + str(host) 424 | 425 | # Add specified command. 426 | command_string = ' '.join(command_list) 427 | 428 | if '"' in command_string: 429 | ssh_command = str(ssh_command) + " '" + str(command_string) + "'" 430 | else: 431 | ssh_command = str(ssh_command) + ' "' + str(command_string) + '"' 432 | 433 | return ssh_command 434 | 435 | def get_right_host_format(self, host): 436 | """ 437 | For host, return host by default. 438 | If host_ip in self.password_host_list, return host_ip. 439 | If host_name in self.password_host_list, return host_name. 440 | """ 441 | right_host_format = host 442 | 443 | if self.password_host_list: 444 | if 'host_name' in self.specified_host_dic[host]: 445 | for host_name in self.specified_host_dic[host]['host_name']: 446 | if host_name in self.password_host_list: 447 | right_host_format = host_name 448 | break 449 | 450 | if (right_host_format == host) and ('host_ip' in self.specified_host_dic[host]): 451 | for host_ip in self.specified_host_dic[host]['host_ip']: 452 | if host_ip in self.password_host_list: 453 | right_host_format = host_ip 454 | break 455 | 456 | return right_host_format 457 | 458 | def execute_ssh_command(self, host, host_ip, ssh_port): 459 | """ 460 | Get complate ssh command and execute it. 461 | """ 462 | # Save log 463 | if self.output_message_level in [3, 4]: 464 | self.save_out('', host=host) 465 | self.save_log('') 466 | 467 | if self.output_message_level == 2: 468 | self.save_out('>>> ' + str(host), end=' ', host=host) 469 | self.save_log('>>> ' + str(host), end=' ') 470 | elif self.output_message_level in [0, 3, 4]: 471 | if host_ip: 472 | self.save_out('>>> ' + str(host) + ' (' + str(host_ip) + ')', host=host) 473 | self.save_log('>>> ' + str(host) + ' (' + str(host_ip) + ')') 474 | else: 475 | self.save_out('>>> ' + str(host), host=host) 476 | self.save_log('>>> ' + str(host)) 477 | 478 | # Get ssh command. 479 | ssh_command = self.get_ssh_command(host, host_ip, ssh_port, self.command_list) 480 | 481 | if self.output_message_level == 4: 482 | self.save_out(' ' + str(ssh_command), host=host) 483 | self.save_log(' ' + str(ssh_command)) 484 | 485 | # Execute ssh command. 486 | # ssh_run usage: 487 | # common_secure.ssh_run(ssh_command, user, host, password, timeout=10) 488 | right_host_format = self.get_right_host_format(host) 489 | stdout_lines = common_secure.ssh_run(ssh_command, self.user, right_host_format, self.password, self.timeout) 490 | 491 | # Print command output message as expected method. 492 | if self.output_message_level == 4: 493 | self.save_out(' ==== output ====', host=host) 494 | self.save_log(' ==== output ====') 495 | 496 | # Auto-rerun for "command missing" and "timeout" conditions. 497 | missing_command = self.check_command_missing(stdout_lines) 498 | missing_command_path = shutil.which(missing_command) 499 | 500 | if missing_command and missing_command_path: 501 | if self.output_message_level == 4: 502 | self.save_out(' Command missing, scp and rerun.', host=host) 503 | self.save_log(' Command missing, scp and rerun.') 504 | 505 | stdout_lines = self.scp_and_rerun(host, host_ip, ssh_port, missing_command_path) 506 | elif self.check_timeout(stdout_lines): 507 | if self.output_message_level == 4: 508 | self.save_out(' Ssh timeout, rerun.', host=host) 509 | self.save_log(' Ssh timeout, rerun.') 510 | 511 | right_host_format = self.get_right_host_format(host) 512 | stdout_lines = common_secure.ssh_run(ssh_command, self.user, right_host_format, self.password, self.timeout) 513 | 514 | if not stdout_lines: 515 | if self.output_message_level == 2: 516 | self.save_out('', host=host) 517 | self.save_log('') 518 | else: 519 | for stdout_line in stdout_lines: 520 | stdout_line = stdout_line.strip() 521 | 522 | if stdout_line: 523 | if self.output_message_level in [1, 2, 3, 4]: 524 | self.save_out(' ' + str(stdout_line), host=host) 525 | 526 | self.save_log(' ' + str(stdout_line)) 527 | 528 | if self.output_message_level == 2: 529 | break 530 | 531 | if self.output_message_level == 4: 532 | self.save_out(' ================', host=host) 533 | self.save_log(' ================') 534 | 535 | def check_command_missing(self, stdout_lines): 536 | """ 537 | Search for command missing string on stdout_lines. 538 | """ 539 | if stdout_lines and (len(stdout_lines) == 1): 540 | for line in stdout_lines: 541 | for command_missing_compile in self.command_missing_compile_list: 542 | if command_missing_compile.match(line): 543 | my_match = command_missing_compile.match(line) 544 | return my_match.group(1) 545 | 546 | return '' 547 | 548 | def check_timeout(self, stdout_lines): 549 | """ 550 | Search for auto rerun string on stdout_lines. 551 | """ 552 | if stdout_lines: 553 | for line in stdout_lines: 554 | for auto_rerun_string in self.timeout_string_list: 555 | if re.search(auto_rerun_string, line): 556 | return True 557 | 558 | return False 559 | 560 | def scp_and_rerun(self, host, host_ip, ssh_port, missing_command_path): 561 | """ 562 | If command missing on remote host, scp missing_command_path to remove host local and rerun. 563 | """ 564 | # Scp command/script to remove host /tmp directory. 565 | script_name = os.path.basename(missing_command_path) 566 | local_script_path = '/tmp/' + str(script_name) 567 | 568 | if ssh_port: 569 | scp_command = 'scp -p -P ' + str(ssh_port) + ' ' + str(missing_command_path) + ' ' + str(host) + ':' + str(local_script_path) 570 | else: 571 | scp_command = 'scp -p ' + str(missing_command_path) + ' ' + str(host) + ':' + str(local_script_path) 572 | 573 | common_secure.scp_run(scp_command, self.user, host, self.password, self.timeout) 574 | 575 | # Re-run command. 576 | command_list = copy.deepcopy(self.command_list) 577 | command_list[0] = local_script_path 578 | ssh_command = self.get_ssh_command(host, host_ip, ssh_port, command_list) 579 | right_host_format = self.get_right_host_format(host) 580 | stdout_lines = common_secure.ssh_run(ssh_command, self.user, right_host_format, self.password, self.timeout) 581 | 582 | return stdout_lines 583 | 584 | def run(self): 585 | """ 586 | Main function, run commands in parallel or serial mode. 587 | """ 588 | # Save command 589 | self.save_command() 590 | start_second = time.time() 591 | 592 | if self.parallel == 1: 593 | host_num = self.serial_run() 594 | else: 595 | host_num = self.parallel_run() 596 | 597 | end_second = time.time() 598 | runtime = self.get_runtime(start_second, end_second) 599 | 600 | print('\nTotal ' + str(host_num) + ' hosts. (Runtime: ' + str(runtime) + ')') 601 | 602 | def serial_run(self): 603 | """ 604 | Run commands in serial mode. 605 | """ 606 | host_num = 0 607 | 608 | for host in self.specified_host_dic.keys(): 609 | if 'host_ip' in self.specified_host_dic[host]: 610 | for (i, host_ip) in enumerate(self.specified_host_dic[host]['host_ip']): 611 | ssh_port = self.specified_host_dic[host]['ssh_port'][i] 612 | host_num += 1 613 | self.execute_ssh_command(host, host_ip, ssh_port) 614 | else: 615 | host_ip = None 616 | ssh_port = None 617 | 618 | if 'ssh_port' in self.specified_host_dic[host]: 619 | ssh_port = self.specified_host_dic[host]['ssh_port'] 620 | 621 | host_num += 1 622 | self.execute_ssh_command(host, host_ip, ssh_port) 623 | 624 | return host_num 625 | 626 | def parallel_run(self): 627 | """ 628 | Run commands in parallel mode. 629 | """ 630 | host_num = 0 631 | thread_list = [] 632 | 633 | # Collect all commands into thread_list. 634 | for host in self.specified_host_dic.keys(): 635 | if 'host_ip' in self.specified_host_dic[host]: 636 | for (i, host_ip) in enumerate(self.specified_host_dic[host]['host_ip']): 637 | ssh_port = self.specified_host_dic[host]['ssh_port'][i] 638 | thread = threading.Thread(target=self.execute_ssh_command, args=(host, host_ip, ssh_port)) 639 | thread.start() 640 | thread_list.append(thread) 641 | else: 642 | host_ip = None 643 | ssh_port = None 644 | 645 | if 'ssh_port' in self.specified_host_dic[host]: 646 | ssh_port = self.specified_host_dic[host]['ssh_port'] 647 | 648 | thread = threading.Thread(target=self.execute_ssh_command, args=(host, host_ip, ssh_port)) 649 | thread.start() 650 | thread_list.append(thread) 651 | 652 | # Run commands in thread_list according to specified parallelism. 653 | alive_thread_list = [] 654 | 655 | for thread in thread_list: 656 | host_num += 1 657 | thread.join() 658 | alive_thread_list.append(thread) 659 | 660 | while self.parallel and (len(alive_thread_list) >= self.parallel): 661 | time.sleep(1) 662 | 663 | for alive_thread in alive_thread_list: 664 | if not alive_thread.is_alive(): 665 | alive_thread_list.remove(alive_thread) 666 | 667 | return host_num 668 | 669 | def get_runtime(self, start_second, end_second): 670 | """ 671 | runtime = end_second - start_second 672 | """ 673 | run_second = int(end_second) - int(start_second) 674 | runtime = str(run_second) + ' seconds' 675 | 676 | if run_second >= 60: 677 | result = divmod(run_second, 60) 678 | run_minute = result[0] 679 | run_second_remainder = result[1] 680 | 681 | if run_minute == 1: 682 | runtime = str(run_minute) + ' minute' 683 | else: 684 | runtime = str(run_minute) + ' minutes' 685 | 686 | if run_second_remainder: 687 | if run_second_remainder == 1: 688 | runtime = str(runtime) + ' ' + str(run_second_remainder) + ' second' 689 | else: 690 | runtime = str(runtime) + ' ' + str(run_second_remainder) + ' seconds' 691 | 692 | return runtime 693 | 694 | 695 | ################ 696 | # Main Process # 697 | ################ 698 | def main(): 699 | (specified_host_dic, user, password, command_list, parallel, timeout, output_message_level, output_file) = read_args() 700 | my_batch_run = BatchRun(specified_host_dic, user, password, command_list, parallel, timeout, output_message_level, output_file) 701 | my_batch_run.run() 702 | 703 | 704 | if __name__ == '__main__': 705 | main() 706 | -------------------------------------------------------------------------------- /common/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/common/__init__.py -------------------------------------------------------------------------------- /common/common_pyqt5.py: -------------------------------------------------------------------------------- 1 | import re 2 | import math 3 | import datetime 4 | import screeninfo 5 | 6 | from PyQt5.QtWidgets import QDesktopWidget, QComboBox, QLineEdit, QListWidget, QCheckBox, QListWidgetItem, QCompleter 7 | from PyQt5.QtGui import QTextCursor, QFont 8 | from PyQt5.Qt import QFontMetrics 9 | from PyQt5.QtCore import Qt, QEvent, QObject 10 | from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg 11 | from matplotlib.figure import Figure 12 | from matplotlib.backends.backend_qt5 import NavigationToolbar2QT 13 | from matplotlib.dates import num2date 14 | 15 | 16 | def center_window(window): 17 | """ 18 | Move the input GUI window into the center of the computer windows. 19 | """ 20 | qr = window.frameGeometry() 21 | cp = QDesktopWidget().availableGeometry().center() 22 | qr.moveCenter(cp) 23 | window.move(qr.topLeft()) 24 | 25 | 26 | def auto_resize(window, width=0, height=0): 27 | """ 28 | Scaling down the window size if screen resolution is smaller than window resolution. 29 | input: Window: Original window; Width: window width; Height: window height 30 | output: Window: Scaled window 31 | """ 32 | # Get default width/height setting. 33 | monitor = screeninfo.get_monitors()[0] 34 | 35 | if not width: 36 | width = monitor.width 37 | 38 | if not height: 39 | height = monitor.height 40 | 41 | # If the screen size is too small, automatically obtain the appropriate length and width value. 42 | if (monitor.width < width) or (monitor.height < height): 43 | width_rate = math.floor((monitor.width / width) * 100) 44 | height_rate = math.floor((monitor.height / height) * 100) 45 | min_rate = min(width_rate, height_rate) 46 | width = int((width * min_rate) / 100) 47 | height = int((height * min_rate) / 100) 48 | 49 | # Resize with auto width/height value. 50 | window.resize(width, height) 51 | 52 | 53 | def text_edit_visible_position(text_edit_item, position='End'): 54 | """ 55 | For QTextEdit widget, show the 'Start' or 'End' part of the text. 56 | """ 57 | cursor = text_edit_item.textCursor() 58 | 59 | if position == 'Start': 60 | cursor.movePosition(QTextCursor.Start) 61 | elif position == 'End': 62 | cursor.movePosition(QTextCursor.End) 63 | 64 | text_edit_item.setTextCursor(cursor) 65 | text_edit_item.ensureCursorVisible() 66 | 67 | 68 | def get_completer(item_list): 69 | """ 70 | Instantiate and config QCompleter. 71 | """ 72 | completer_ins = QCompleter(item_list) 73 | 74 | # Enable Qt.MatchContains mode (just like re.search()), not Qt.MatchStartsWith or Qt.MatchEndsWith. 75 | completer_ins.setFilterMode(Qt.MatchContains) 76 | # Match upper/lower case. 77 | completer_ins.setCaseSensitivity(Qt.CaseInsensitive) 78 | 79 | # Adjust the appropriate size of the item. 80 | if item_list: 81 | list_view = completer_ins.popup() 82 | max_length = max(len(item) for item in item_list) 83 | popup_width = list_view.fontMetrics().width('w' * max_length) 84 | list_view.setFixedWidth(popup_width) 85 | 86 | return completer_ins 87 | 88 | 89 | class MyCheckBox(QCheckBox): 90 | """ 91 | Re-Write eventFilter function for QCheckBox. 92 | """ 93 | def __init__(self, *args, **kwargs): 94 | super().__init__(*args, **kwargs) 95 | self.installEventFilter(self) 96 | 97 | def eventFilter(self, watched, event): 98 | """ 99 | Make sure clicking on the blank section still takes effect. 100 | """ 101 | if (watched == self) and (event.type() == QEvent.MouseButtonPress): 102 | if self.rect().contains(event.pos()): 103 | self.toggle() 104 | return True 105 | 106 | return super().eventFilter(watched, event) 107 | 108 | 109 | class ComboBoxEventFilter(QObject): 110 | def __init__(self, comboBox, *args, **kwargs): 111 | super().__init__(*args, **kwargs) 112 | self.comboBox = comboBox 113 | self.droppedDown = False 114 | 115 | def eventFilter(self, obj, event): 116 | # MouseButtonPress 117 | if event.type() == 3: 118 | self.droppedDown = True 119 | # MouseLeave 120 | elif event.type() == 11: 121 | self.droppedDown = False 122 | 123 | return super().eventFilter(obj, event) 124 | 125 | 126 | class QComboCheckBox(QComboBox): 127 | """ 128 | QComboCheckBox is a QComboBox with checkbox. 129 | """ 130 | def __init__(self, parent): 131 | super(QComboCheckBox, self).__init__(parent) 132 | 133 | # self.qLineWidget is used to load QCheckBox items. 134 | self.qListWidget = QListWidget() 135 | self.setModel(self.qListWidget.model()) 136 | self.setView(self.qListWidget) 137 | 138 | # self.qLineEdit is used to show selected items on QLineEdit. 139 | self.qLineEdit = QLineEdit() 140 | self.qLineEdit.textChanged.connect(self.validQLineEditValue) 141 | self.qLineEdit.setReadOnly(True) 142 | self.setLineEdit(self.qLineEdit) 143 | 144 | # self.checkBoxList is used to save QCheckBox items. 145 | self.checkBoxList = [] 146 | 147 | # Adjust width for new item. 148 | self.dropDownBoxWidthPixel = self.width() 149 | 150 | self.eventFilter = ComboBoxEventFilter(self) 151 | self.view().viewport().installEventFilter(self.eventFilter) 152 | 153 | def hidePopup(self): 154 | if self.eventFilter.droppedDown: 155 | return 156 | else: 157 | return super().hidePopup() 158 | 159 | def validQLineEditValue(self): 160 | """ 161 | Make sure value of self.qLineEdit always match selected items. 162 | """ 163 | selectedItemString = ' '.join(self.selectedItems().values()) 164 | 165 | if self.qLineEdit.text() != selectedItemString: 166 | self.updateLineEdit() 167 | 168 | def addCheckBoxItems(self, text_list): 169 | """ 170 | Add multi QCheckBox format items. 171 | """ 172 | for text in text_list: 173 | self.addCheckBoxItem(text) 174 | 175 | def addCheckBoxItem(self, text, update_width=False): 176 | """ 177 | Add QCheckBox format item into QListWidget(QComboCheckBox). 178 | """ 179 | qItem = QListWidgetItem(self.qListWidget) 180 | qBox = MyCheckBox(text) 181 | qBox.stateChanged.connect(self.qBoxStateChanged) 182 | self.checkBoxList.append(qBox) 183 | self.qListWidget.setItemWidget(qItem, qBox) 184 | 185 | if update_width: 186 | self.updateDropDownBoxWidth(text, qBox) 187 | 188 | def qBoxStateChanged(self, checkState): 189 | """ 190 | Post process for qBox state change. 191 | """ 192 | itemText = self.sender().text() 193 | 194 | self.updateItemSelectedState(itemText, checkState) 195 | self.updateLineEdit() 196 | 197 | def updateItemSelectedState(self, itemText, checkState): 198 | """ 199 | If "ALL" is selected, unselect other items. 200 | If other item is selected, unselect "ALL" item. 201 | """ 202 | if checkState != 0: 203 | selectedItemDic = self.selectedItems() 204 | selectedItemList = list(selectedItemDic.values()) 205 | 206 | if itemText == 'ALL': 207 | if len(selectedItemList) > 1: 208 | for (i, qBox) in enumerate(self.checkBoxList): 209 | if (qBox.text() in selectedItemList) and (qBox.text() != 'ALL'): 210 | self.checkBoxList[i].setChecked(False) 211 | else: 212 | if 'ALL' in selectedItemList: 213 | for (i, qBox) in enumerate(self.checkBoxList): 214 | if qBox.text() == 'ALL': 215 | self.checkBoxList[i].setChecked(False) 216 | break 217 | 218 | def updateLineEdit(self): 219 | """ 220 | Update QComboCheckBox show message with self.qLineEdit. 221 | """ 222 | selectedItemString = ' '.join(self.selectedItems().values()) 223 | self.qLineEdit.setReadOnly(False) 224 | self.qLineEdit.clear() 225 | self.qLineEdit.setText(selectedItemString) 226 | self.qLineEdit.setReadOnly(True) 227 | 228 | def updateDropDownBoxWidth(self, text, qBox): 229 | """ 230 | Update self.dropDownBoxWidthPixel. 231 | """ 232 | fm = QFontMetrics(QFont()) 233 | textPixel = fm.width(text) 234 | indicatorPixel = int(qBox.iconSize().width() * 1.4) 235 | 236 | if textPixel > self.dropDownBoxWidthPixel: 237 | self.dropDownBoxWidthPixel = textPixel 238 | self.view().setMinimumWidth(self.dropDownBoxWidthPixel + indicatorPixel) 239 | 240 | def updateDropDownBoxHeight(self): 241 | fm = QFontMetrics(QFont()) 242 | fontPixel = fm.height() + 2 243 | self.setStyleSheet(f""" 244 | QComboBox QAbstractItemView::item {{ 245 | min-height: {fontPixel}px; 246 | padding: 0px; 247 | margin: 0px; 248 | }} 249 | """) 250 | 251 | def selectedItems(self): 252 | """ 253 | Get all selected items (location and value). 254 | """ 255 | selectedItemDic = {} 256 | 257 | for (i, qBox) in enumerate(self.checkBoxList): 258 | if qBox.isChecked() is True: 259 | selectedItemDic.setdefault(i, qBox.text()) 260 | 261 | return selectedItemDic 262 | 263 | def selectAllItems(self): 264 | """ 265 | Select all items. 266 | """ 267 | for (i, qBox) in enumerate(self.checkBoxList): 268 | if qBox.isChecked() is False: 269 | self.checkBoxList[i].setChecked(True) 270 | 271 | def unselectAllItems(self): 272 | """ 273 | Unselect all items. 274 | """ 275 | for (i, qBox) in enumerate(self.checkBoxList): 276 | if qBox.isChecked() is True: 277 | self.checkBoxList[i].setChecked(False) 278 | 279 | def clear(self): 280 | """ 281 | Clear all items. 282 | """ 283 | super().clear() 284 | self.checkBoxList = [] 285 | 286 | 287 | class FigureCanvasQTAgg(FigureCanvasQTAgg): 288 | """ 289 | Generate a new figure canvas. 290 | """ 291 | def __init__(self): 292 | self.figure = Figure() 293 | self.axes = None 294 | super().__init__(self.figure) 295 | 296 | 297 | class NavigationToolbar2QT(NavigationToolbar2QT): 298 | """ 299 | Enhancement for NavigationToolbar2QT, can get and show label value. 300 | """ 301 | def __init__(self, canvas, parent, coordinates=True, x_is_date=True): 302 | super().__init__(canvas, parent, coordinates) 303 | self.x_is_date = x_is_date 304 | 305 | @staticmethod 306 | def bisection(event_xdata, xdata_list): 307 | xdata = None 308 | index = None 309 | lower = 0 310 | upper = len(xdata_list) - 1 311 | bisection_index = (upper - lower) // 2 312 | 313 | if xdata_list: 314 | if event_xdata > xdata_list[upper]: 315 | xdata = xdata_list[upper] 316 | index = upper 317 | elif (event_xdata < xdata_list[lower]) or (len(xdata_list) <= 2): 318 | xdata = xdata_list[lower] 319 | index = lower 320 | elif event_xdata in xdata_list: 321 | xdata = event_xdata 322 | index = xdata_list.index(event_xdata) 323 | 324 | while xdata is None: 325 | if upper - lower == 1: 326 | if event_xdata - xdata_list[lower] <= xdata_list[upper] - event_xdata: 327 | xdata = xdata_list[lower] 328 | index = lower 329 | else: 330 | xdata = xdata_list[upper] 331 | index = upper 332 | 333 | break 334 | 335 | if event_xdata > xdata_list[bisection_index]: 336 | lower = bisection_index 337 | elif event_xdata < xdata_list[bisection_index]: 338 | upper = bisection_index 339 | 340 | bisection_index = (upper - lower) // 2 + lower 341 | 342 | return xdata, index 343 | 344 | def _mouse_event_to_message(self, event): 345 | if event.inaxes and event.inaxes.get_navigate(): 346 | try: 347 | if self.x_is_date: 348 | event_xdata = num2date(event.xdata).strftime('%Y,%m,%d,%H,%M,%S') 349 | else: 350 | event_xdata = event.xdata 351 | except (ValueError, OverflowError): 352 | pass 353 | else: 354 | if self.x_is_date and (len(event_xdata.split(',')) == 6): 355 | (year, month, day, hour, minute, second) = event_xdata.split(',') 356 | event_xdata = datetime.datetime(int(year), int(month), int(day), int(hour), int(minute), int(second)) 357 | 358 | xdata_list = list(self.canvas.figure.gca().get_lines()[0].get_xdata()) 359 | (xdata, index) = self.bisection(event_xdata, sorted(xdata_list)) 360 | 361 | if xdata is not None: 362 | info_list = [] 363 | 364 | for line in self.canvas.figure.gca().get_lines(): 365 | label = line.get_label() 366 | ydata_string = line.get_ydata() 367 | ydata_list = list(ydata_string) 368 | ydata = ydata_list[index] 369 | 370 | info_list.append('%s=%s' % (label, ydata)) 371 | 372 | info_string = ' '.join(info_list) 373 | 374 | if self.x_is_date: 375 | xdata_string = xdata.strftime('%Y-%m-%d %H:%M:%S') 376 | xdata_string = re.sub(r' 00:00:00', '', xdata_string) 377 | info_string = '[%s]\n%s' % (xdata_string, info_string) 378 | 379 | return info_string 380 | return '' 381 | -------------------------------------------------------------------------------- /common/common_secure.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/common/common_secure.so -------------------------------------------------------------------------------- /config/host.list: -------------------------------------------------------------------------------- 1 | #### Format #### 2 | # [group] 3 | # host_ip1 4 | # host_ip2 ssh_port= 5 | # host_ip3 ssh_host= 6 | # host_ip4 ssh_host= ssh_port= 7 | # sub_group5 8 | # ~host_ip6 9 | # ~host_name7 10 | # ~sub_group8 11 | ################ 12 | 13 | -------------------------------------------------------------------------------- /data/demo/command_line_run_demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/demo/command_line_run_demo.gif -------------------------------------------------------------------------------- /data/demo/gui_info_demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/demo/gui_info_demo.gif -------------------------------------------------------------------------------- /data/demo/gui_run_demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/demo/gui_run_demo.gif -------------------------------------------------------------------------------- /data/pictures/G.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/G.png -------------------------------------------------------------------------------- /data/pictures/H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/H.png -------------------------------------------------------------------------------- /data/pictures/N.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/N.png -------------------------------------------------------------------------------- /data/pictures/Z.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/Z.png -------------------------------------------------------------------------------- /data/pictures/about.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/about.png -------------------------------------------------------------------------------- /data/pictures/cancel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/cancel.png -------------------------------------------------------------------------------- /data/pictures/close.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/close.png -------------------------------------------------------------------------------- /data/pictures/database.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/database.png -------------------------------------------------------------------------------- /data/pictures/exit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/exit.png -------------------------------------------------------------------------------- /data/pictures/fail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/fail.png -------------------------------------------------------------------------------- /data/pictures/gun.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/gun.png -------------------------------------------------------------------------------- /data/pictures/load.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/load.png -------------------------------------------------------------------------------- /data/pictures/log.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/log.png -------------------------------------------------------------------------------- /data/pictures/magnifier.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/magnifier.png -------------------------------------------------------------------------------- /data/pictures/monitor.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/monitor.ico -------------------------------------------------------------------------------- /data/pictures/open.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/open.png -------------------------------------------------------------------------------- /data/pictures/pend.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/pend.png -------------------------------------------------------------------------------- /data/pictures/radar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/radar.png -------------------------------------------------------------------------------- /data/pictures/save.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/save.png -------------------------------------------------------------------------------- /data/pictures/select.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/select.png -------------------------------------------------------------------------------- /data/pictures/slow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/slow.png -------------------------------------------------------------------------------- /data/pictures/switch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/switch.png -------------------------------------------------------------------------------- /data/pictures/trace.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/trace.png -------------------------------------------------------------------------------- /data/pictures/version.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/data/pictures/version.png -------------------------------------------------------------------------------- /db/host_asset/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/db/host_asset/.gitignore -------------------------------------------------------------------------------- /db/host_info/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/db/host_info/.gitignore -------------------------------------------------------------------------------- /db/host_queue/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/db/host_queue/.gitignore -------------------------------------------------------------------------------- /db/host_stat/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/db/host_stat/.gitignore -------------------------------------------------------------------------------- /db/network_scan/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/db/network_scan/.gitignore -------------------------------------------------------------------------------- /docs/batchRun_user_manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/docs/batchRun_user_manual.pdf -------------------------------------------------------------------------------- /install.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import sys 4 | 5 | CWD = os.getcwd() 6 | PYTHON_PATH = os.path.dirname(os.path.abspath(sys.executable)) 7 | 8 | 9 | def check_python_version(): 10 | """ 11 | Check python version. 12 | python3 is required, anaconda3 is better. 13 | """ 14 | print('>>> Check python version.') 15 | 16 | current_python = sys.version_info[:2] 17 | required_python = (3, 12) 18 | 19 | if current_python < required_python: 20 | sys.stderr.write(""" 21 | ============================ 22 | Not suggested python version 23 | ============================ 24 | batchRun requires Python {}.{}, 25 | Current python is Python {}.{}. 26 | """.format(*(required_python + current_python))) 27 | sys.exit(1) 28 | else: 29 | print(' Required python version : ' + str(required_python)) 30 | print(' Current python version : ' + str(current_python)) 31 | 32 | 33 | def get_ld_library_path_setting(): 34 | """ 35 | Get variable LD_LIBRARY_PATH setting for batchRun. 36 | """ 37 | python_lib_path = re.sub('/bin', '/lib', PYTHON_PATH) 38 | ld_library_path_setting = 'export LD_LIBRARY_PATH=$BATCH_RUN_INSTALL_PATH/lib:' + str(python_lib_path) + ':' 39 | 40 | if 'LD_LIBRARY_PATH' in os.environ: 41 | if python_lib_path in str(os.environ['LD_LIBRARY_PATH']): 42 | ld_library_path_setting = str(ld_library_path_setting) + re.sub(str(python_lib_path) + ':', '', os.environ['LD_LIBRARY_PATH']) 43 | else: 44 | ld_library_path_setting = str(ld_library_path_setting) + str(os.environ['LD_LIBRARY_PATH']) 45 | 46 | return ld_library_path_setting 47 | 48 | 49 | def gen_batch_run(): 50 | """ 51 | Generate script /bin/batch_run. 52 | """ 53 | batch_run = str(CWD) + '/bin/batch_run' 54 | ld_library_path_setting = get_ld_library_path_setting() 55 | 56 | print('') 57 | print('>>> Generate script "' + str(batch_run) + '".') 58 | 59 | try: 60 | with open(batch_run, 'w') as BR: 61 | BR.write("""#!/bin/bash 62 | 63 | # Set python3 path. 64 | export PATH=""" + str(PYTHON_PATH) + """:$PATH 65 | 66 | # Set install path. 67 | export BATCH_RUN_INSTALL_PATH=""" + str(CWD) + """ 68 | 69 | # Set LD_LIBRARY_PATH. 70 | """ + str(ld_library_path_setting) + """ 71 | 72 | # Preprocess "command" argument. 73 | pre_arg="" 74 | num=-1 75 | 76 | for arg in "$@" 77 | do 78 | if [[ $pre_arg == "-c" ]] || [[ $pre_arg == "--command" ]]; then 79 | if [[ $arg =~ " " ]] && [[ $arg =~ "-" ]]; then 80 | arg=`echo $arg | sed 's/-/\\\\\\-/g'` 81 | fi 82 | fi 83 | 84 | num=$(($num+1)) 85 | args[$num]=$arg 86 | pre_arg=$arg 87 | done 88 | 89 | # Execute batch_run.py. 90 | python3 $BATCH_RUN_INSTALL_PATH/bin/batch_run.py ${args[*]} 91 | """) 92 | 93 | os.chmod(batch_run, 0o755) 94 | except Exception as err: 95 | print('*Error*: Failed on generating script "' + str(batch_run) + '": ' + str(err)) 96 | sys.exit(1) 97 | 98 | 99 | def gen_shell_tools(): 100 | """ 101 | Generate shell scripts under . 102 | """ 103 | tool_list = ['bin/batch_run_gui', 'tools/encrypt_python', 'tools/network_scan', 'tools/patch', 'tools/sample_host_info', 'tools/sample_host_queue', 'tools/sample_host_stat', 'tools/save_password', 'tools/show_top_file', 'tools/switch_etc_hosts'] 104 | ld_library_path_setting = get_ld_library_path_setting() 105 | 106 | for tool_name in tool_list: 107 | tool = str(CWD) + '/' + str(tool_name) 108 | 109 | print('') 110 | print('>>> Generate script "' + str(tool) + '".') 111 | 112 | try: 113 | with open(tool, 'w') as SP: 114 | SP.write("""#!/bin/bash 115 | 116 | # Set python3 path. 117 | export PATH=""" + str(PYTHON_PATH) + """:$PATH 118 | 119 | # Set install path. 120 | export BATCH_RUN_INSTALL_PATH=""" + str(CWD) + """ 121 | 122 | # Set LD_LIBRARY_PATH. 123 | """ + str(ld_library_path_setting) + """ 124 | 125 | # Execute """ + str(tool_name) + """.py. 126 | python3 $BATCH_RUN_INSTALL_PATH/""" + str(tool_name) + '.py $@') 127 | 128 | os.chmod(tool, 0o755) 129 | except Exception as error: 130 | print('*Error*: Failed on generating script "' + str(tool) + '": ' + str(error)) 131 | sys.exit(1) 132 | 133 | 134 | def gen_config_file(): 135 | """ 136 | Generate config file /config/config.py. 137 | """ 138 | config_file = str(CWD) + '/config/config.py' 139 | 140 | print('') 141 | print('>>> Generate config file "' + str(config_file) + '".') 142 | 143 | if os.path.exists(config_file): 144 | print('*Warning*: config file "' + str(config_file) + '" already exists, will not update it.') 145 | else: 146 | try: 147 | host_list = str(CWD) + '/config/host.list' 148 | 149 | with open(config_file, 'w') as CF: 150 | CF.write("""# Specify host list, default is "host.list" on current configure directory. 151 | host_list = '""" + str(host_list) + """' 152 | 153 | # Specify the database directory. 154 | db_path = '""" + str(CWD) + """/db' 155 | 156 | # Default ssh command. 157 | default_ssh_command = 'ssh -o StrictHostKeyChecking=no -t -q' 158 | 159 | # Define timeout for ssh command, unit is "second". 160 | serial_timeout = 10 161 | parallel_timeout = 20 162 | 163 | # Illegal command list. 164 | illegal_command_list = ['rm -rf /', 'rm -rf ~', 'rm -rf ~/'] 165 | 166 | # Command for switch_etc_hosts. 167 | switch_etc_hosts_command = '""" + str(CWD) + """/tools/switch_etc_hosts --rewrite --tool batchRun' 168 | 169 | # Command for network_scan. 170 | network_scan_command = '""" + str(CWD) + """/tools/network_scan --alive' 171 | 172 | # Command for sample_host_info. 173 | sample_host_info_command = '""" + str(CWD) + """/tools/sample_host_info --groups ALL' 174 | 175 | # Command for sample_host_queue. 176 | sample_host_queue_command = '""" + str(CWD) + """/tools/sample_host_queue --groups ALL' 177 | 178 | # Command for sample_host_stat. 179 | sample_host_stat_command = '""" + str(CWD) + """/tools/sample_host_stat --groups ALL' 180 | """) 181 | 182 | os.chmod(config_file, 0o777) 183 | except Exception as error: 184 | print('*Error*: Failed on opening config file "' + str(config_file) + '" for write: ' + str(error)) 185 | sys.exit(1) 186 | 187 | 188 | ################ 189 | # Main Process # 190 | ################ 191 | def main(): 192 | check_python_version() 193 | gen_batch_run() 194 | gen_shell_tools() 195 | gen_config_file() 196 | 197 | print('') 198 | print('Done, Please enjoy it.') 199 | 200 | 201 | if __name__ == '__main__': 202 | main() 203 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | cryptography==43.0.3 2 | matplotlib==3.9.2 3 | pandas==2.2.3 4 | pexpect==4.9.0 5 | PyQt5==5.15.11 6 | qdarkstyle==3.2.3 7 | screeninfo==0.8.1 8 | -------------------------------------------------------------------------------- /scripts/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bytedance/batchRun/58cc1f9d236ca5e6c6c5a96564941366e87c5db8/scripts/.gitignore -------------------------------------------------------------------------------- /scripts/cleanup/clean_tmp.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | /bin/tmpwatch -amv 14d /tmp 4 | -------------------------------------------------------------------------------- /scripts/cleanup/drop_caches.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo 3 > /proc/sys/vm/drop_caches 4 | -------------------------------------------------------------------------------- /scripts/ssh/nopassword_ssh.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Run this script only if the /home direcotry is a shared direcotry. 3 | 4 | cd ~/.ssh 5 | rm -f id_rsa id_rsa.pub 6 | ssh-keygen -t rsa -N "" -f id_rsa 7 | cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys 8 | chmod 600 ~/.ssh/authorized_keys 9 | -------------------------------------------------------------------------------- /tools/encrypt_python.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ################################ 3 | # File Name : encrypt_python.py 4 | # Author : liyanqing 5 | # Created On : 2021-08-17 09:08:33 6 | # Description : 7 | ################################ 8 | import os 9 | import re 10 | import sys 11 | import argparse 12 | 13 | os.environ['PYTHONUNBUFFERED'] = '1' 14 | 15 | 16 | def read_args(): 17 | """ 18 | Read in arguments. 19 | """ 20 | parser = argparse.ArgumentParser() 21 | 22 | parser.add_argument('-f', '--python_files', 23 | required=True, 24 | nargs='+', 25 | default=[], 26 | help='Specify python files want to encrypt.') 27 | 28 | args = parser.parse_args() 29 | 30 | return args.python_files 31 | 32 | 33 | def gen_setup_file(python_files): 34 | setup_file = str(os.getcwd()) + '/encrypt_python_setup.py' 35 | 36 | print('>>> Write setup file "' + str(setup_file) + '".') 37 | 38 | try: 39 | with open(setup_file, 'w') as EF: 40 | EF.write('import os\n') 41 | EF.write('from setuptools import setup\n') 42 | EF.write('from Cython.Build import cythonize\n') 43 | EF.write('\n') 44 | EF.write('python_files = [') 45 | 46 | for python_file in python_files: 47 | EF.write("'" + str(python_file) + "', ") 48 | 49 | EF.write(']\n') 50 | EF.write("os.environ['CFLAGS']='-std=c99'\n") 51 | EF.write('\n') 52 | EF.write('setup(ext_modules = cythonize(python_files),)\n') 53 | except Exception as error: 54 | print('*Error*: Failed on open setup file "' + str(setup_file) + '" for write, ' + str(error)) 55 | sys.exit(1) 56 | 57 | return setup_file 58 | 59 | 60 | def execute_setup_file(setup_file): 61 | command = 'python3 ' + str(setup_file) + ' build_ext --inplace' 62 | 63 | print('>>> Executing setup file ...') 64 | print(' ' + str(command)) 65 | 66 | os.system(command) 67 | 68 | 69 | def cleanup_directory(python_files, setup_file): 70 | setup_file_name = re.sub(r'.*/', '', setup_file) 71 | for file_name in os.listdir(os.getcwd()): 72 | if file_name == setup_file_name: 73 | command = 'rm -rf ' + str(setup_file) 74 | print(' ' + str(command)) 75 | os.system(command) 76 | elif (file_name == 'build') and os.path.isdir(file_name): 77 | command = 'rm -rf ' + str(file_name) 78 | print(' ' + str(command)) 79 | os.system(command) 80 | elif re.match(r'^.*\.c$', file_name): 81 | for python_file in python_files: 82 | python_file_name = re.sub(r'\.py', '', python_file) 83 | 84 | if re.match(r'^' + str(python_file_name) + r'\.c$', file_name): 85 | command = 'rm -rf ' + str(file_name) 86 | print(' ' + str(command)) 87 | os.system(command) 88 | break 89 | elif re.match(r'^.*\.so$', file_name): 90 | for python_file in python_files: 91 | python_file_name = re.sub(r'\.py', '', python_file) 92 | 93 | if re.match(r'^' + str(python_file_name) + r'.*\.so$', file_name): 94 | command = 'mv ' + str(file_name) + ' ' + str(python_file_name) + '.so' 95 | print(' ' + str(command)) 96 | os.system(command) 97 | break 98 | 99 | 100 | ################ 101 | # Main Process # 102 | ################ 103 | def main(): 104 | (python_files) = read_args() 105 | setup_file = gen_setup_file(python_files) 106 | execute_setup_file(setup_file) 107 | cleanup_directory(python_files, setup_file) 108 | 109 | 110 | if __name__ == '__main__': 111 | main() 112 | -------------------------------------------------------------------------------- /tools/message.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import sys 4 | import argparse 5 | 6 | from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QFrame, QGridLayout, QLabel 7 | from PyQt5.QtCore import Qt 8 | 9 | sys.path.insert(0, str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/common') 10 | import common_pyqt5 11 | 12 | os.environ['PYTHONUNBUFFERED'] = '1' 13 | 14 | 15 | def read_args(): 16 | """ 17 | Read in arguments. 18 | """ 19 | parser = argparse.ArgumentParser() 20 | 21 | parser.add_argument('-t', '--title', 22 | nargs='+', 23 | default=['Message',], 24 | help='Specify message title, default is "Message".') 25 | parser.add_argument('-m', '--message', 26 | required=True, 27 | nargs='+', 28 | help='Required argument, specified message (text).') 29 | 30 | args = parser.parse_args() 31 | title_string = ' '.join(args.title) 32 | message_string = ' '.join(args.message) 33 | 34 | return title_string, message_string 35 | 36 | 37 | class ShowMessage(QMainWindow): 38 | def __init__(self, title, message): 39 | super().__init__() 40 | self.title = title 41 | self.message = message 42 | 43 | self.init_ui() 44 | 45 | def init_ui(self): 46 | # Add main_tab 47 | self.main_tab = QTabWidget(self) 48 | self.setCentralWidget(self.main_tab) 49 | 50 | self.main_frame = QFrame(self.main_tab) 51 | 52 | # Grid 53 | main_grid = QGridLayout() 54 | main_grid.addWidget(self.main_frame, 0, 0) 55 | self.main_tab.setLayout(main_grid) 56 | 57 | # Generate main_table 58 | self.gen_main_frame() 59 | 60 | # Show main window 61 | self.setWindowTitle(self.title) 62 | common_pyqt5.auto_resize(self, 400, 50) 63 | common_pyqt5.center_window(self) 64 | 65 | def gen_main_frame(self): 66 | self.message_label = QLabel(self.main_frame) 67 | self.message_label.setText(self.message) 68 | self.message_label.setAlignment(Qt.AlignCenter) 69 | 70 | # Grid 71 | main_frame_grid = QGridLayout() 72 | main_frame_grid.addWidget(self.message_label, 0, 0) 73 | self.main_frame.setLayout(main_frame_grid) 74 | 75 | 76 | ################ 77 | # Main Process # 78 | ################ 79 | def main(): 80 | (title, message) = read_args() 81 | app = QApplication(sys.argv) 82 | my_show_message = ShowMessage(title, message) 83 | my_show_message.show() 84 | sys.exit(app.exec_()) 85 | 86 | 87 | if __name__ == '__main__': 88 | main() 89 | -------------------------------------------------------------------------------- /tools/network_scan.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ################################ 3 | # File Name : network_scan.py 4 | # Author : liyanqing.1987 5 | # Created On : 2025-01-09 10:01:20 6 | # Description : scan network with ping. 7 | ################################ 8 | import os 9 | import re 10 | import sys 11 | import json 12 | import time 13 | import copy 14 | import argparse 15 | import ipaddress 16 | import threading 17 | 18 | sys.path.append(str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/config') 19 | import config 20 | 21 | sys.path.insert(0, os.environ['BATCH_RUN_INSTALL_PATH']) 22 | from common import common 23 | 24 | os.environ['PYTHONUNBUFFERED'] = '1' 25 | CWD = os.getcwd() 26 | 27 | 28 | def read_args(): 29 | """ 30 | Read in arguments. 31 | """ 32 | parser = argparse.ArgumentParser() 33 | 34 | parser.add_argument('-a', '--alive', 35 | action='store_true', 36 | default=False, 37 | help='Only show systems that are alive.') 38 | parser.add_argument('-p', '--parallel', 39 | type=int, 40 | default=1000, 41 | help='Specify the parallelism of the ip scanning, default is "1000".') 42 | parser.add_argument('-d', '--debug', 43 | action='store_true', 44 | default=False, 45 | help='Enable debug mode.') 46 | parser.add_argument('-i', '--input_file', 47 | default=str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/config/network.list', 48 | help='Read network setting from file, default is "config/network.list".') 49 | parser.add_argument('-o', '--output_file', 50 | default=str(config.db_path) + '/network_scan/network_scan.json', 51 | help='Save scan result into json file, default is "/network_scan/network_scan.json".') 52 | 53 | args = parser.parse_args() 54 | 55 | # Check input_file. 56 | if not os.path.exists(args.input_file): 57 | common.bprint('"' + str(args.input_file) + '": No such input file.', level='Error') 58 | sys.exit(1) 59 | 60 | # Check output_dir. 61 | output_dir = os.path.dirname(args.output_file) 62 | 63 | if not os.path.exists(output_dir): 64 | common.bprint('Not find output directory "' + str(output_dir) + '".', level='Error') 65 | sys.exit(1) 66 | 67 | return args.alive, args.parallel, args.debug, args.input_file, args.output_file 68 | 69 | 70 | class NetworkScan(): 71 | def __init__(self, alive, parallel, debug, input_file, output_file): 72 | self.alive = alive 73 | self.parallel = parallel 74 | self.debug = debug 75 | self.input_file = input_file 76 | self.output_file = output_file 77 | self.output_dic = {} 78 | 79 | def debug_print(self, message): 80 | if self.debug: 81 | common.bprint(message, date_format='%Y%m%d %H:%M:%S') 82 | 83 | def parse_input_file(self): 84 | """ 85 | Input file line format shoue be like below: 86 | ---------------- 87 | zone ip/ip_range/cidr 88 | ---------------- 89 | """ 90 | self.debug_print('>>> Parsing input file "' + str(self.input_file) + '" ...') 91 | input_dic = {} 92 | 93 | with open(self.input_file, 'r') as IF: 94 | for line in IF.readlines(): 95 | if re.match(r'^\s*$', line) or re.match(r'^\s*#.*#', line): 96 | continue 97 | elif re.match(r'^\s*(\S+)\s+(\S+)\s*$', line): 98 | my_match = re.match(r'^\s*(\S+)\s+(\S+)\s*$', line) 99 | zone = my_match.group(1) 100 | network = my_match.group(2) 101 | input_dic.setdefault(zone, {}) 102 | input_dic[zone].setdefault(network, []) 103 | self.output_dic.setdefault(zone, {}) 104 | self.output_dic[zone].setdefault(network, {}) 105 | 106 | if re.match(r'^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$', network): 107 | # For ip format. 108 | input_dic[zone][network].append(network) 109 | self.output_dic[zone][network].setdefault(network, {'connectivity': False, 'packet': 0, 'received': 0, 'packet_loss': '', 'rtt_avg': 0.0, 'rtt_unit': ''}) 110 | elif re.match(r'^(((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3})(25[0-5]|2[0-4]\d|[01]?\d\d?)-(\d+)$', network): 111 | # For ip_range format. 112 | my_match = re.match(r'^(((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3})(25[0-5]|2[0-4]\d|[01]?\d\d?)-(\d+)$', network) 113 | pre_ip = my_match.group(1) 114 | init_num = int(my_match.group(4)) 115 | final_num = int(my_match.group(5)) 116 | 117 | if init_num >= final_num: 118 | common.bprint('Invalid line on "' + str(self.input_file) + '".', level='Error') 119 | common.bprint(line, color='red', display_method=1, indent=9) 120 | sys.exit(1) 121 | else: 122 | for num in range(init_num, final_num+1): 123 | ip = str(pre_ip) + str(num) 124 | input_dic[zone][network].append(ip) 125 | self.output_dic[zone][network].setdefault(ip, {'connectivity': False, 'packet': 0, 'received': 0, 'packet_loss': '', 'rtt_avg': 0.0, 'rtt_unit': ''}) 126 | elif re.match(r'^(((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3})(25[0-5]|2[0-4]\d|[01]?\d\d?)/(\d+)$', network): 127 | # For cidr format. 128 | ip_list = list(ipaddress.IPv4Network(network).hosts()) 129 | del ip_list[0] 130 | 131 | for ip in ip_list: 132 | ip = str(ip) 133 | input_dic[zone][network].append(ip) 134 | self.output_dic[zone][network].setdefault(ip, {'connectivity': False, 'packet': 0, 'received': 0, 'packet_loss': '', 'rtt_avg': 0.0, 'rtt_unit': ''}) 135 | else: 136 | common.bprint('Invalid line on "' + str(self.input_file) + '".', level='Error') 137 | common.bprint(line, color='red', display_method=1, indent=9) 138 | sys.exit(1) 139 | 140 | return input_dic 141 | 142 | def network_scan(self, input_dic): 143 | self.debug_print('>>> Scaning network ...') 144 | thread_list = [] 145 | 146 | for zone in input_dic.keys(): 147 | for network in input_dic[zone].keys(): 148 | for ip in input_dic[zone][network]: 149 | thread = threading.Thread(target=self.ping_ip, args=(zone, network, ip)) 150 | thread_list.append(thread) 151 | 152 | # Run commands in thread_list in parallel. 153 | alive_thread_list = [] 154 | 155 | for thread in thread_list: 156 | thread.start() 157 | alive_thread_list.append(thread) 158 | 159 | while self.parallel and (len(alive_thread_list) >= self.parallel): 160 | time.sleep(1) 161 | tmp_thread_list = copy.copy(alive_thread_list) 162 | 163 | for alive_thread in tmp_thread_list: 164 | if not alive_thread.is_alive(): 165 | alive_thread_list.remove(alive_thread) 166 | 167 | for alive_thread in alive_thread_list: 168 | alive_thread.join() 169 | 170 | # Remove "connectivity == False" 171 | tmp_output_dic = copy.deepcopy(self.output_dic) 172 | 173 | if self.alive: 174 | for zone in tmp_output_dic.keys(): 175 | for network in tmp_output_dic[zone].keys(): 176 | for ip in tmp_output_dic[zone][network].keys(): 177 | if not tmp_output_dic[zone][network][ip]['connectivity']: 178 | del self.output_dic[zone][network][ip] 179 | 180 | def ping_ip(self, zone, network, ip): 181 | """ 182 | ping pass output format: 183 | ---------------- 184 | [liyanqing.1987@n232-134-073 tools]$ ping -w 3 10.212.204.140 185 | PING 10.212.204.140 (10.212.204.140) 56(84) bytes of data. 186 | 64 bytes from 10.212.204.140: icmp_seq=1 ttl=55 time=0.196 ms 187 | 64 bytes from 10.212.204.140: icmp_seq=2 ttl=55 time=0.181 ms 188 | 64 bytes from 10.212.204.140: icmp_seq=3 ttl=55 time=0.177 ms 189 | 64 bytes from 10.212.204.140: icmp_seq=4 ttl=55 time=0.183 ms 190 | 191 | --- 10.212.204.140 ping statistics --- 192 | 4 packets transmitted, 4 received, 0% packet loss, time 2999ms 193 | rtt min/avg/max/mdev = 0.177/0.184/0.196/0.011 ms 194 | ---------------- 195 | 196 | ping fail output format: 197 | ---------------- 198 | [liyanqing.1987@n232-134-073 tools]$ ping -w 3 10.249.75.243 199 | PING 10.249.75.243 (10.249.75.243) 56(84) bytes of data. 200 | 201 | --- 10.249.75.243 ping statistics --- 202 | 4 packets transmitted, 0 received, 100% packet loss, time 2999ms 203 | ---------------- 204 | """ 205 | self.debug_print(' Scaning ' + str(zone) + ' ' + str(network) + ' ' + str(ip)) 206 | 207 | packets_compile = re.compile(r'^\s*(\d+)\s+packets transmitted,\s+(\d+)\s+received,\s+(\d+%)\s+packet loss,.*$') 208 | rtt_compile = re.compile(r'^\s*rtt min/avg/max/mdev = [\d\.]+/([\d\.]+)/[\d\.]+/[\d\.]+ (\S+)\s*') 209 | command = 'ping -w 3 ' + str(ip) 210 | (return_code, stdout, stderr) = common.run_command(command) 211 | 212 | for line in str(stdout, 'utf-8').split('\n'): 213 | if packets_compile.match(line): 214 | my_match = packets_compile.match(line) 215 | packet = int(my_match.group(1)) 216 | received = int(my_match.group(2)) 217 | packet_loss = my_match.group(3) 218 | self.output_dic[zone][network][ip]['packet'] = packet 219 | self.output_dic[zone][network][ip]['received'] = received 220 | self.output_dic[zone][network][ip]['packet_loss'] = packet_loss 221 | 222 | if packet and received: 223 | self.output_dic[zone][network][ip]['connectivity'] = True 224 | elif (ip in self.output_dic[zone][network]) and rtt_compile.match(line): 225 | my_match = rtt_compile.match(line) 226 | rtt_avg = float(my_match.group(1)) 227 | rtt_unit = my_match.group(2) 228 | self.output_dic[zone][network][ip]['rtt_avg'] = rtt_avg 229 | self.output_dic[zone][network][ip]['rtt_unit'] = rtt_unit 230 | 231 | def write_output_file(self): 232 | self.debug_print('>>> Write output file "' + str(self.output_file) + '" ...') 233 | 234 | with open(self.output_file, 'w') as OF: 235 | OF.write(str(json.dumps(self.output_dic, ensure_ascii=False, indent=4)) + '\n') 236 | 237 | def run(self): 238 | input_dic = self.parse_input_file() 239 | self.network_scan(input_dic) 240 | self.write_output_file() 241 | 242 | 243 | ################ 244 | # Main Process # 245 | ################ 246 | def main(): 247 | (alive, parallel, debug, input_file, output_file) = read_args() 248 | my_network_scan = NetworkScan(alive, parallel, debug, input_file, output_file) 249 | my_network_scan.run() 250 | 251 | 252 | if __name__ == '__main__': 253 | main() 254 | -------------------------------------------------------------------------------- /tools/patch.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import re 4 | import sys 5 | import shutil 6 | import filecmp 7 | import argparse 8 | 9 | sys.path.insert(0, str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/common') 10 | import common 11 | 12 | os.environ['PYTHONUNBUFFERED'] = '1' 13 | 14 | 15 | def read_args(): 16 | """ 17 | Read in arguments. 18 | """ 19 | parser = argparse.ArgumentParser() 20 | 21 | parser.add_argument('-p', '--patch_path', 22 | default='', 23 | help='Specify patch path (new install package path).') 24 | 25 | args = parser.parse_args() 26 | 27 | if not os.path.exists(args.patch_path): 28 | common.bprint('"' + str(args.path_path) + '": No such patch path.', level='Error') 29 | sys.exit(1) 30 | 31 | return args.patch_path 32 | 33 | 34 | class Patch(): 35 | def __init__(self, patch_path): 36 | self.install_path = os.path.realpath(os.environ['BATCH_RUN_INSTALL_PATH']) 37 | self.patch_path = os.path.realpath(patch_path) 38 | self.ignore_py_list = ['config/config.py',] 39 | 40 | print('Install Path : ' + str(self.install_path)) 41 | print('Patch path : ' + str(self.patch_path)) 42 | print('') 43 | 44 | self.check_path_name() 45 | 46 | def check_path_name(self): 47 | """ 48 | Make sure install_path and the patch_path have the same directory name. 49 | """ 50 | if os.path.basename(self.install_path) != os.path.basename(self.patch_path): 51 | common.bprint('Current install path name is "' + str(os.path.basename(self.install_path)) + '", but patch path name is "' + str(os.path.basename(self.patch_path)) + '".', level='Warning') 52 | 53 | choice = input('Do you want to continue? (y|n) ') 54 | 55 | if (choice == 'n') or (choice == 'N') or (choice == 'no'): 56 | os.sys.exit(0) 57 | else: 58 | print('') 59 | 60 | def get_py_list(self, specified_path): 61 | """ 62 | Get all python files from specified_path with relative path format. 63 | """ 64 | py_list = [] 65 | 66 | for root_path, c_dirs, c_files in os.walk(specified_path): 67 | for c_file in c_files: 68 | if re.match(r'^.*\.py$', c_file) and os.path.isfile(str(root_path) + '/' + str(c_file)): 69 | if root_path == specified_path: 70 | py_file = c_file 71 | else: 72 | relative_path = re.sub(str(specified_path) + '/', '', root_path) 73 | py_file = str(relative_path) + '/' + str(c_file) 74 | 75 | py_list.append(py_file) 76 | 77 | return py_list 78 | 79 | def run(self): 80 | """ 81 | Compare python files with self.install_path and self.patch_path. 82 | Copy new files into self.install_path. 83 | copy updated files into self.install_path. 84 | """ 85 | install_py_list = self.get_py_list(self.install_path) 86 | patch_py_list = self.get_py_list(self.patch_path) 87 | 88 | for py_file in patch_py_list: 89 | if py_file not in self.ignore_py_list: 90 | abs_install_py = str(self.install_path) + '/' + str(py_file) 91 | abs_patch_py = str(self.patch_path) + '/' + str(py_file) 92 | 93 | if (py_file not in install_py_list) or (not filecmp.cmp(abs_install_py, abs_patch_py)): 94 | # Remove old python file. 95 | if py_file in install_py_list: 96 | print('> Remove old python file "' + str(abs_install_py) + '".') 97 | 98 | try: 99 | os.remove(abs_install_py) 100 | except Exception as error: 101 | common.bprint('Failed on removing old python file "' + str(abs_install_py) + '".', level='Error') 102 | common.bprint(error, color='red', display_method=1, indent=9) 103 | sys.exit(1) 104 | 105 | # Create directory for new python file. 106 | abs_install_path = os.path.dirname(abs_install_py) 107 | 108 | if not os.path.exists(abs_install_path): 109 | print('> Create directory "' + str(abs_install_path) + '".') 110 | 111 | try: 112 | os.makedirs(abs_install_path) 113 | except Exception as error: 114 | common.bprint('Failed on creating directory "' + str(abs_install_path) + '".', level='Error') 115 | common.bprint(error, color='red', display_method=1, indent=9) 116 | sys.exit(1) 117 | 118 | # Copy path python file into install path. 119 | print('> Copy python file "' + str(abs_patch_py) + '" into "' + str(abs_install_py) + '".') 120 | 121 | try: 122 | shutil.copyfile(abs_patch_py, abs_install_py) 123 | except Exception as error: 124 | common.bprint('Failed on copying file "' + str(abs_patch_py) + '" into "' + str(abs_install_py) + '".', level='Error') 125 | common.bprint(error, color='red', display_method=1, indent=9) 126 | sys.exit(1) 127 | 128 | 129 | ################ 130 | # Main Process # 131 | ################ 132 | def main(): 133 | (patch_path) = read_args() 134 | my_patch = Patch(patch_path) 135 | my_patch.run() 136 | 137 | 138 | if __name__ == '__main__': 139 | main() 140 | -------------------------------------------------------------------------------- /tools/sample_host_info.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ################################ 3 | # File Name : sample_host_info.py 4 | # Author : liyanqing.1987 5 | # Created On : 2024-08-12 18:34:15 6 | # Description : Used to sample host os and hardware info. 7 | ################################ 8 | import os 9 | import re 10 | import sys 11 | import json 12 | import datetime 13 | import argparse 14 | 15 | sys.path.append(str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/config') 16 | import config 17 | 18 | sys.path.insert(0, os.environ['BATCH_RUN_INSTALL_PATH']) 19 | from common import common 20 | 21 | os.environ['PYTHONUNBUFFERED'] = '1' 22 | CWD = os.getcwd() 23 | 24 | 25 | def read_args(): 26 | """ 27 | Read in arguments. 28 | """ 29 | parser = argparse.ArgumentParser() 30 | 31 | parser.add_argument('-H', '--hosts', 32 | nargs='+', 33 | default=[], 34 | help='Specify host(s) for batch_run.') 35 | parser.add_argument('-G', '--groups', 36 | nargs='+', 37 | default=[], 38 | help='Specify host group(s) for batch_run.') 39 | parser.add_argument('-u', '--user', 40 | default='', 41 | help='Specify the user identity for SSH login to specified host.') 42 | parser.add_argument('-p', '--password', 43 | default='', 44 | help='Specify the user password for SSH login to specified host.') 45 | parser.add_argument('-P', '--parallel', 46 | type=int, 47 | default=0, 48 | help='Specify the parallelism for batch_run.') 49 | parser.add_argument('-t', '--timeout', 50 | type=int, 51 | default=20, 52 | help='Specify the timeout for batch_run.') 53 | parser.add_argument('-o', '--output_dir', 54 | default=str(config.db_path) + '/host_info', 55 | help='Specify host info output directory, default is "/host_info".') 56 | 57 | args = parser.parse_args() 58 | 59 | # Check output_dir. 60 | if os.path.exists(args.output_dir): 61 | args.output_dir = os.path.realpath(args.output_dir) 62 | else: 63 | common.bprint('"' + str(args.output_dir) + '": No such directory.', level='Error') 64 | sys.exit(1) 65 | 66 | return args.hosts, args.groups, args.user, args.password, args.parallel, args.timeout, args.output_dir 67 | 68 | 69 | class SampleHostInfo(): 70 | def __init__(self, host_list, group_list, user, password, parallel, timeout, output_dir): 71 | self.batch_run_command = self.get_batch_run_command(host_list, group_list, user, password, parallel, timeout) 72 | self.output_dir = output_dir 73 | self.host_list_file = str(self.output_dir) + '/host_list.json' 74 | self.latest_host_info_file = str(self.output_dir) + '/host_info.json' 75 | self.old_host_info_file = os.path.realpath(self.latest_host_info_file) 76 | current_time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") 77 | self.current_host_info_file = str(self.output_dir) + '/host_info.json.' + str(current_time) 78 | 79 | def get_batch_run_command(self, host_list=[], group_list=[], user='', password='', parallel=0, timeout=20): 80 | """ 81 | Get default batch_run command (without run command). 82 | """ 83 | batch_run_command = str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/bin/batch_run' 84 | 85 | if host_list: 86 | batch_run_command = str(batch_run_command) + ' --hosts ' + str(' '.join(host_list)) 87 | 88 | if group_list: 89 | batch_run_command = str(batch_run_command) + ' --groups ' + str(' '.join(group_list)) 90 | 91 | if user: 92 | batch_run_command = str(batch_run_command) + ' --user ' + str(user) 93 | 94 | if password: 95 | batch_run_command = str(batch_run_command) + ' --password ' + str(password) 96 | 97 | batch_run_command = str(batch_run_command) + ' --parallel ' + str(parallel) 98 | 99 | if timeout: 100 | batch_run_command = str(batch_run_command) + ' --timeout ' + str(timeout) 101 | 102 | return batch_run_command 103 | 104 | def cleanup(self): 105 | command = 'rm -rf *.info host_list.json' 106 | common.bprint('\n>>> Clean up ' + str(self.output_dir) + ' ...') 107 | common.bprint(command, indent=4) 108 | os.chdir(self.output_dir) 109 | os.system(command) 110 | os.chdir(CWD) 111 | 112 | def sample_host_list_info(self): 113 | command = str(self.batch_run_command) + ' --list --output_file ' + str(self.host_list_file) 114 | common.bprint('\n>>> Sampling host list information ...') 115 | common.bprint(command, indent=4) 116 | os.system(command) 117 | 118 | def sample_host_os_hard_info(self): 119 | sample_command = 'lsb_release -a; hostnamectl; lscpu; free -g' 120 | command = str(self.batch_run_command) + ' --command "' + str(sample_command) + '" --output_message_level 1 --output_file ' + str(self.output_dir) + '/HOST.info' 121 | common.bprint('\n>>> Sampling host os/cpu/mem information ...') 122 | common.bprint(command, indent=4) 123 | os.system(command) 124 | 125 | def collect_host_os_hard_info(self): 126 | common.bprint('\n>>> Collecting host information ...') 127 | host_list_dic = {} 128 | 129 | if os.path.exists(self.host_list_file): 130 | with open(self.host_list_file, 'r') as HLF: 131 | host_list_dic = json.loads(HLF.read()) 132 | 133 | host_info_dic = self.collect_host_info(host_list_dic) 134 | host_info_dic = self.update_host_info(host_info_dic) 135 | 136 | with open(self.current_host_info_file, 'w') as HIF: 137 | HIF.write(str(json.dumps(host_info_dic, ensure_ascii=False, indent=4)) + '\n') 138 | 139 | common.bprint('Host info has been saved to file "' + str(self.current_host_info_file) + '".', indent=4) 140 | 141 | def collect_host_info(self, host_list_dic): 142 | """ 143 | Collect host os/hardware information from sampled files under self.output_dir. 144 | """ 145 | host_info_dic = {} 146 | 147 | # Get host_info_dic based on *.info files. 148 | server_type_compile = re.compile(r'^\s*Chassis:\s*(\S*)\s*$') 149 | os1_compile = re.compile(r'^\s*Description:\s*(.+?)\s*$') 150 | os2_compile = re.compile(r'^\s*Operating System:.*?([A-Z].+?\)).*$') 151 | cpu_architecture_compile = re.compile(r'^\s*Architecture:\s*(\S+)\s*$') 152 | cpu_thread_compile = re.compile(r'^\s*CPU\(s\):\s*(\d+)\s*$') 153 | thread_per_core_compile = re.compile(r'^\s*Thread\(s\) per core:\s*(\d+)\s*$') 154 | cpu_model_compile = re.compile(r'^\s*Model name:\s*(.+?)\s*$') 155 | cpu_frequency_compile = re.compile(r'^\s*CPU MHz:\s*([0-9\.]+)\s*$') 156 | mem_size_compile = re.compile(r'^\s*Mem:\s*(\d+)\s+.*$') 157 | swap_size_compile = re.compile(r'^\s*Swap:\s*(\d+)\s+.*$') 158 | 159 | for host_ip in host_list_dic.keys(): 160 | host_info_dic.setdefault(host_ip, {'host_name': [], 161 | 'groups': [], 162 | 'server_type': '', 163 | 'os': '', 164 | 'cpu_architecture': '', 165 | 'cpu_thread': 0, 166 | 'thread_per_core': 0, 167 | 'cpu_model': '', 168 | 'cpu_frequency': 0.0, 169 | 'cpu_frequency_unit': 'GHz', 170 | 'mem_size': 0, 171 | 'mem_size_unit': 'GB', 172 | 'swap_size': 0, 173 | 'swap_size_unit': 'GB'}) 174 | 175 | if 'host_name' in host_list_dic[host_ip]: 176 | host_info_dic[host_ip]['host_name'] = host_list_dic[host_ip]['host_name'] 177 | 178 | if 'groups' in host_list_dic[host_ip]: 179 | host_info_dic[host_ip]['groups'] = host_list_dic[host_ip]['groups'] 180 | 181 | host_info_file = str(self.output_dir) + '/' + str(host_ip) + '.info' 182 | 183 | if os.path.exists(host_info_file): 184 | with open(host_info_file, 'r') as HIF: 185 | for line in HIF.readlines(): 186 | if server_type_compile.match(line): 187 | my_match = server_type_compile.match(line) 188 | host_info_dic[host_ip]['server_type'] = my_match.group(1) 189 | elif os1_compile.match(line): 190 | my_match = os1_compile.match(line) 191 | host_info_dic[host_ip]['os'] = my_match.group(1) 192 | elif os2_compile.match(line): 193 | if not host_info_dic[host_ip]['os']: 194 | my_match = os2_compile.match(line) 195 | host_info_dic[host_ip]['os'] = my_match.group(1) 196 | elif cpu_architecture_compile.match(line): 197 | my_match = cpu_architecture_compile.match(line) 198 | host_info_dic[host_ip]['cpu_architecture'] = my_match.group(1) 199 | elif cpu_thread_compile.match(line): 200 | my_match = cpu_thread_compile.match(line) 201 | host_info_dic[host_ip]['cpu_thread'] = int(my_match.group(1)) 202 | elif thread_per_core_compile.match(line): 203 | my_match = thread_per_core_compile.match(line) 204 | host_info_dic[host_ip]['thread_per_core'] = int(my_match.group(1)) 205 | elif cpu_model_compile.match(line): 206 | my_match = cpu_model_compile.match(line) 207 | host_info_dic[host_ip]['cpu_model'] = my_match.group(1) 208 | elif cpu_frequency_compile.match(line): 209 | my_match = cpu_frequency_compile.match(line) 210 | host_info_dic[host_ip]['cpu_frequency'] = round(float(my_match.group(1))/1000, 1) 211 | elif mem_size_compile.match(line): 212 | my_match = mem_size_compile.match(line) 213 | host_info_dic[host_ip]['mem_size'] = int(my_match.group(1)) 214 | elif swap_size_compile.match(line): 215 | my_match = swap_size_compile.match(line) 216 | host_info_dic[host_ip]['swap_size'] = int(my_match.group(1)) 217 | 218 | return host_info_dic 219 | 220 | def update_host_info(self, host_info_dic): 221 | """ 222 | Get old host_info_dic from self.old_host_info_file. 223 | If host_info missing on host_info_dic, get it from old host_info_dic. 224 | """ 225 | old_host_info_dic = {} 226 | 227 | if os.path.exists(self.old_host_info_file): 228 | with open(self.old_host_info_file, 'r') as OHIF: 229 | old_host_info_dic = json.loads(OHIF.read()) 230 | 231 | if old_host_info_dic: 232 | for host in host_info_dic.keys(): 233 | if (not host_info_dic[host]['os']) and (host in old_host_info_dic) and old_host_info_dic[host]['os']: 234 | common.bprint('Host information is empty for "' + str(host) + '", reset it with old host_info.json file.', indent=4, level='Warning') 235 | host_info_dic[host] = old_host_info_dic[host] 236 | 237 | return host_info_dic 238 | 239 | def link_host_info_file(self): 240 | common.bprint('\n>>> Link current host info file into host_info.json') 241 | common.bprint('ln -s ' + str(self.current_host_info_file) + ' ' + str(self.latest_host_info_file), indent=4) 242 | 243 | if os.path.exists(self.latest_host_info_file): 244 | try: 245 | os.remove(self.latest_host_info_file) 246 | except Exception as error: 247 | common.bprint('Failed on removing ' + str(self.latest_host_info_file) + '": ' + str(error), indent=4, level='Error') 248 | sys.exit(1) 249 | 250 | try: 251 | os.symlink(self.current_host_info_file, self.latest_host_info_file) 252 | except Exception as error: 253 | common.bprint('Failed on Linking "' + str(self.current_host_info_file) + '" into "' + str(self.latest_host_info_file) + '": ' + str(error), indent=4, level='Error') 254 | sys.exit(1) 255 | 256 | def sample_host_info(self): 257 | # Clean up self.output_dir. 258 | self.cleanup() 259 | 260 | # Sample host list information. 261 | self.sample_host_list_info() 262 | 263 | # Sample host os/cpu/mem information. 264 | self.sample_host_os_hard_info() 265 | 266 | # Collect host os/cpu/mem information. 267 | self.collect_host_os_hard_info() 268 | 269 | # Link self.current_host_info_file into self.latest_host_info_file. 270 | self.link_host_info_file() 271 | 272 | 273 | ################ 274 | # Main Process # 275 | ################ 276 | def main(): 277 | (hosts, groups, user, password, parallel, timeout, output_dir) = read_args() 278 | my_sample_host_info = SampleHostInfo(hosts, groups, user, password, parallel, timeout, output_dir) 279 | my_sample_host_info.sample_host_info() 280 | 281 | 282 | if __name__ == '__main__': 283 | main() 284 | -------------------------------------------------------------------------------- /tools/sample_host_queue.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ################################ 3 | # File Name : sample_host_queue.py 4 | # Author : liyanqing.1987 5 | # Created On : 2024-12-30 16:55:15 6 | # Description : Used to sample host queue info. 7 | ################################ 8 | import os 9 | import re 10 | import sys 11 | import json 12 | import datetime 13 | import argparse 14 | 15 | sys.path.append(str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/config') 16 | import config 17 | 18 | sys.path.insert(0, str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/common') 19 | import common 20 | import common_lsf 21 | 22 | os.environ['PYTHONUNBUFFERED'] = '1' 23 | CWD = os.getcwd() 24 | 25 | 26 | def read_args(): 27 | """ 28 | Read in arguments. 29 | """ 30 | parser = argparse.ArgumentParser() 31 | 32 | parser.add_argument('-H', '--hosts', 33 | nargs='+', 34 | default=[], 35 | help='Specify host(s) for batch_run.') 36 | parser.add_argument('-G', '--groups', 37 | nargs='+', 38 | default=[], 39 | help='Specify host group(s) for batch_run.') 40 | parser.add_argument('-u', '--user', 41 | default='', 42 | help='Specify the user identity for SSH login to specified host.') 43 | parser.add_argument('-p', '--password', 44 | default='', 45 | help='Specify the user password for SSH login to specified host.') 46 | parser.add_argument('-P', '--parallel', 47 | type=int, 48 | default=0, 49 | help='Specify the parallelism for batch_run, default is "0".') 50 | parser.add_argument('-t', '--timeout', 51 | type=int, 52 | default=20, 53 | help='Specify the timeout for batch_run, default is "20".') 54 | parser.add_argument('-i', '--host_info_json', 55 | default=str(config.db_path) + '/host_info/host_info.json', 56 | help='Specify host info file to collect host static information, default is "' + str(config.db_path) + '/host_info/host_info.json".') 57 | parser.add_argument('-o', '--output_dir', 58 | default=str(config.db_path) + '/host_queue', 59 | help='Specify host info output directory, default is "' + str(config.db_path) + '/host_queue".') 60 | 61 | args = parser.parse_args() 62 | 63 | # Check and update output_dir. 64 | if os.path.exists(args.output_dir): 65 | args.output_dir = os.path.realpath(args.output_dir) 66 | else: 67 | common.bprint('"' + str(args.output_dir) + '": No such directory.', level='Error') 68 | sys.exit(1) 69 | 70 | return args.hosts, args.groups, args.user, args.password, args.parallel, args.timeout, args.host_info_json, args.output_dir 71 | 72 | 73 | class SampleHostQueue(): 74 | def __init__(self, host_list, group_list, user, password, parallel, timeout, host_info_json, output_dir): 75 | self.host_list = host_list 76 | self.group_list = group_list 77 | self.user = user 78 | self.password = password 79 | self.parallel = parallel 80 | self.timeout = timeout 81 | self.output_dir = output_dir 82 | self.latest_host_queue_file = str(self.output_dir) + '/host_queue.json' 83 | current_time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") 84 | self.current_host_queue_file = str(self.output_dir) + '/host_queue.json.' + str(current_time) 85 | self.host_info_dic = self.parse_host_info_json(host_info_json) 86 | 87 | def parse_host_info_json(self, host_info_json): 88 | host_info_dic = {} 89 | 90 | if os.path.exists(host_info_json): 91 | with open(host_info_json, 'r') as HIJ: 92 | host_info_dic = json.loads(HIJ.read()) 93 | 94 | return host_info_dic 95 | 96 | def cleanup_with_suffix(self, suffix_list=['lsid', 'queues', 'hosts', 'bmgroup']): 97 | common.bprint('\n>>> Cleaning up files with suffixs "' + '|'.join(suffix_list) + '" ...') 98 | 99 | for root, dirs, files in os.walk(self.output_dir): 100 | for file in files: 101 | for suffix in suffix_list: 102 | if file.endswith(suffix): 103 | file_path = os.path.join(root, file) 104 | os.remove(file_path) 105 | 106 | def get_batch_run_command(self, host_list=[], group_list=[], user='', password='', parallel=0, timeout=20): 107 | """ 108 | Get default batch_run command (without run command). 109 | """ 110 | batch_run_command = str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/bin/batch_run' 111 | 112 | if host_list: 113 | batch_run_command = str(batch_run_command) + ' --hosts ' + str(' '.join(host_list)) 114 | 115 | if group_list: 116 | batch_run_command = str(batch_run_command) + ' --groups ' + str(' '.join(group_list)) 117 | 118 | if user: 119 | batch_run_command = str(batch_run_command) + ' --user ' + str(user) 120 | 121 | if password: 122 | batch_run_command = str(batch_run_command) + ' --password ' + str(password) 123 | 124 | batch_run_command = str(batch_run_command) + ' --parallel ' + str(parallel) 125 | 126 | if timeout: 127 | batch_run_command = str(batch_run_command) + ' --timeout ' + str(timeout) 128 | 129 | return batch_run_command 130 | 131 | def sample_host_lsid_info(self, host_list, group_list): 132 | """ 133 | Sample host lsid info with command "lsid". 134 | """ 135 | common.bprint('\n>>> Sampling host lsid information ...') 136 | sample_command = 'source /etc/profile; lsid' 137 | batch_run_command = self.get_batch_run_command(host_list, group_list, self.user, self.password, self.parallel, self.timeout) 138 | command = str(batch_run_command) + ' --command "' + str(sample_command) + '" --output_message_level 1 --output_file ' + str(self.output_dir) + '/HOST.lsid' 139 | common.bprint(command, indent=4) 140 | os.system(command) 141 | 142 | def collect_host_lsid_info(self): 143 | """ 144 | Collect host lsid info with function common_lsf.get_lsid_info(). 145 | Return cluster_host_dic: scheduler -> cluster -> host_ip. 146 | Return host_lsid_dic: host_ip -> scheduler/version/cluster/master. 147 | """ 148 | common.bprint('\n>>> Collecting host lsid information ...') 149 | cluster_host_dic = {} 150 | host_lsid_dic = {} 151 | 152 | for root, dirs, files in os.walk(self.output_dir): 153 | for file in files: 154 | if re.match(r'^(\S+)\.lsid$', file): 155 | my_match = re.match(r'^(\S+)\.lsid$', file) 156 | host_ip = my_match.group(1) 157 | host_lsid_dic[host_ip] = {'scheduler': '', 'version': '', 'cluster': '', 'master': ''} 158 | file_path = os.path.join(root, file) 159 | (tool, tool_version, cluster, master) = common_lsf.get_lsid_info(command='cat ' + str(file_path)) 160 | 161 | if tool: 162 | host_lsid_dic[host_ip] = {'scheduler': tool, 'version': tool_version, 'cluster': cluster, 'master': master} 163 | cluster_host_dic.setdefault(tool, {}) 164 | cluster_host_dic[tool].setdefault(cluster, []) 165 | cluster_host_dic[tool][cluster].append(host_ip) 166 | 167 | return cluster_host_dic, host_lsid_dic 168 | 169 | def sample_cluster_host_info(self, cluster_host_dic): 170 | """ 171 | Sample queue-host relationship with command "bqueues/bhosts/bmgroup". 172 | """ 173 | common.bprint('\n>>> Sampling cluster host information ...') 174 | 175 | for scheduler in cluster_host_dic.keys(): 176 | for cluster in cluster_host_dic[scheduler].keys(): 177 | first_host = cluster_host_dic[scheduler][cluster][0] 178 | 179 | common.bprint('* Sampling queues information for scheduler "' + str(scheduler) + '" cluster "' + str(cluster) + '" on host "' + str(first_host) + '" ...', indent=4) 180 | sample_command = 'source /etc/profile; bqueues -l' 181 | batch_run_command = self.get_batch_run_command([first_host], [], self.user, self.password, 1, self.timeout) 182 | cluster_queues_file = str(self.output_dir) + '/' + str(scheduler) + '_' + str(cluster) + '.bqueues' 183 | command = str(batch_run_command) + ' --command "' + str(sample_command) + '" --output_message_level 1 --output_file ' + str(cluster_queues_file) 184 | common.bprint(command, indent=4) 185 | os.system(command) 186 | 187 | common.bprint('* Sampling hosts information for scheduler "' + str(scheduler) + '" cluster "' + str(cluster) + '" on host "' + str(first_host) + '" ...', indent=4) 188 | sample_command = 'source /etc/profile; bhosts -w' 189 | batch_run_command = self.get_batch_run_command([first_host], [], self.user, self.password, 1, self.timeout) 190 | cluster_hosts_file = str(self.output_dir) + '/' + str(scheduler) + '_' + str(cluster) + '.bhosts' 191 | command = str(batch_run_command) + ' --command "' + str(sample_command) + '" --output_message_level 1 --output_file ' + str(cluster_hosts_file) 192 | common.bprint(command, indent=4) 193 | os.system(command) 194 | 195 | common.bprint('* Sampling host group information for scheduler "' + str(scheduler) + '" cluster "' + str(cluster) + '" on host "' + str(first_host) + '" ...', indent=4) 196 | sample_command = 'source /etc/profile; bmgroup -w -r' 197 | batch_run_command = self.get_batch_run_command([first_host], [], self.user, self.password, 1, self.timeout) 198 | cluster_bmgroup_file = str(self.output_dir) + '/' + str(scheduler) + '_' + str(cluster) + '.bmgroup' 199 | command = str(batch_run_command) + ' --command "' + str(sample_command) + '" --output_message_level 1 --output_file ' + str(cluster_bmgroup_file) 200 | common.bprint(command, indent=4) 201 | os.system(command) 202 | 203 | def collect_host_queue_info(self, host_lsid_dic): 204 | """ 205 | Collect queue-host relationship with function common_lsf.get_queue_host_info(). 206 | Return host_queue_dic: host_ip -> scheduler/version/cluster/queue_list. 207 | """ 208 | common.bprint('\n>>> Collecting host cheduler/cluster/queue information ...') 209 | 210 | # Initalize host_queue_dic. 211 | host_queue_dic = {} 212 | 213 | for host_ip in host_lsid_dic.keys(): 214 | host_queue_dic.setdefault(host_ip, {'scheduler': '', 'cluster': '', 'queues': ''}) 215 | 216 | # Collect tmp host queue info with tmp_dic. 217 | tmp_dic = {} 218 | 219 | for root, dirs, files in os.walk(self.output_dir): 220 | for file in files: 221 | if re.match(r'^(\S+)\.bqueues$', file): 222 | my_match = re.match(r'^(\S+)\.bqueues$', file) 223 | host_ip = my_match.group(1) 224 | file_path = os.path.join(root, file) 225 | tmp_dic.setdefault(host_ip, {}) 226 | tmp_dic[host_ip].setdefault('bqueues_file', file_path) 227 | elif re.match(r'^(\S+)\.bhosts$', file): 228 | my_match = re.match(r'^(\S+)\.bhosts$', file) 229 | host_ip = my_match.group(1) 230 | file_path = os.path.join(root, file) 231 | tmp_dic.setdefault(host_ip, {}) 232 | tmp_dic[host_ip].setdefault('bhosts_file', file_path) 233 | elif re.match(r'^(\S+)\.bmgroup$', file): 234 | my_match = re.match(r'^(\S+)\.bmgroup$', file) 235 | host_ip = my_match.group(1) 236 | file_path = os.path.join(root, file) 237 | tmp_dic.setdefault(host_ip, {}) 238 | tmp_dic[host_ip].setdefault('bmgroup_file', file_path) 239 | 240 | # lsf_host_queue_dic: host <-> queues. 241 | # self.host_info_dic: host_ip <-> host_name. 242 | # host_lsid_dic: host <-> scheduler/version/cluster/master. 243 | for host_ip in tmp_dic.keys(): 244 | if ('bqueues_file' in tmp_dic[host_ip]) and ('bhosts_file' in tmp_dic[host_ip]) and ('bmgroup_file' in tmp_dic[host_ip]): 245 | lsf_host_queue_dic = common_lsf.get_host_queue_info(command='cat ' + str(tmp_dic[host_ip]['bqueues_file']), get_hosts_list_command='cat ' + str(tmp_dic[host_ip]['bhosts_file']), get_bmgroup_info_command='cat ' + str(tmp_dic[host_ip]['bmgroup_file'])) 246 | 247 | if lsf_host_queue_dic: 248 | for host in self.host_info_dic.keys(): 249 | if (host in host_lsid_dic) and ('host_name' in self.host_info_dic[host]): 250 | for host_name in self.host_info_dic[host]['host_name']: 251 | if host_name in lsf_host_queue_dic.keys(): 252 | host_queue_dic[host] = {'scheduler': str(host_lsid_dic[host]['scheduler']) + '_' + str(host_lsid_dic[host]['version']), 'cluster': host_lsid_dic[host]['cluster'], 'queues': lsf_host_queue_dic[host_name]} 253 | 254 | return host_queue_dic 255 | 256 | def write_host_queue_file(self, host_queue_dic): 257 | common.bprint('\n>>> Write host scheduler/cluster/queue relationship file ...') 258 | 259 | with open(self.current_host_queue_file, 'w') as HQF: 260 | HQF.write(str(json.dumps(host_queue_dic, ensure_ascii=False, indent=4)) + '\n') 261 | 262 | common.bprint('Host queue info has been saved to file "' + str(self.current_host_queue_file) + '".', indent=4) 263 | 264 | def link_host_queue_file(self): 265 | common.bprint('\n>>> Link current host queue file into host_queue.json') 266 | common.bprint('ln -s ' + str(self.current_host_queue_file) + ' ' + str(self.latest_host_queue_file), indent=4) 267 | 268 | if os.path.exists(self.latest_host_queue_file): 269 | try: 270 | os.remove(self.latest_host_queue_file) 271 | except Exception as error: 272 | common.bprint('Failed on removing ' + str(self.latest_host_queue_file) + '": ' + str(error), indent=4, level='Error') 273 | sys.exit(1) 274 | 275 | try: 276 | os.symlink(self.current_host_queue_file, self.latest_host_queue_file) 277 | except Exception as error: 278 | common.bprint('Failed on Linking "' + str(self.current_host_queue_file) + '" into "' + str(self.latest_host_queue_file) + '": ' + str(error), indent=4, level='Error') 279 | sys.exit(1) 280 | 281 | def sample_host_queue(self): 282 | # Cleanup self.output_dir. 283 | self.cleanup_with_suffix() 284 | 285 | # Sample host lsid info. 286 | self.sample_host_lsid_info(self.host_list, self.group_list) 287 | 288 | # Collect host lsid info. 289 | (cluster_host_dic, host_lsid_dic) = self.collect_host_lsid_info() 290 | self.cleanup_with_suffix(suffix_list=['lsid', ]) 291 | 292 | # Sample cluster host info. 293 | self.sample_cluster_host_info(cluster_host_dic) 294 | 295 | # Collect cluster host info. 296 | host_queue_dic = self.collect_host_queue_info(host_lsid_dic) 297 | self.cleanup_with_suffix(suffix_list=['queues', 'hosts', 'bmgroup']) 298 | 299 | # Write self.current_host_queue_file with host_queue_dic. 300 | self.write_host_queue_file(host_queue_dic) 301 | 302 | # Link self.current_host_queue_file into self.latest_host_queue_file. 303 | self.link_host_queue_file() 304 | 305 | 306 | ################ 307 | # Main Process # 308 | ################ 309 | def main(): 310 | (hosts, groups, user, password, parallel, timeout, host_info_json, output_dir) = read_args() 311 | my_sample_host_queue = SampleHostQueue(hosts, groups, user, password, parallel, timeout, host_info_json, output_dir) 312 | my_sample_host_queue.sample_host_queue() 313 | 314 | 315 | if __name__ == '__main__': 316 | main() 317 | -------------------------------------------------------------------------------- /tools/sample_host_stat.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ################################ 3 | # File Name : sample_host_stat.py 4 | # Author : liyanqing.1987 5 | # Created On : 2024-12-16 09:30:15 6 | # Description : Used to sample host stat info. 7 | ################################ 8 | import os 9 | import re 10 | import sys 11 | import json 12 | import datetime 13 | import argparse 14 | 15 | sys.path.append(str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/config') 16 | import config 17 | 18 | sys.path.insert(0, os.environ['BATCH_RUN_INSTALL_PATH']) 19 | from common import common 20 | 21 | os.environ['PYTHONUNBUFFERED'] = '1' 22 | CWD = os.getcwd() 23 | 24 | 25 | def read_args(): 26 | """ 27 | Read in arguments. 28 | """ 29 | parser = argparse.ArgumentParser() 30 | 31 | parser.add_argument('-H', '--hosts', 32 | nargs='+', 33 | default=[], 34 | help='Specify host(s) for batch_run.') 35 | parser.add_argument('-G', '--groups', 36 | nargs='+', 37 | default=[], 38 | help='Specify host group(s) for batch_run.') 39 | parser.add_argument('-u', '--user', 40 | default='', 41 | help='Specify the user identity for SSH login to specified host.') 42 | parser.add_argument('-p', '--password', 43 | default='', 44 | help='Specify the user password for SSH login to specified host.') 45 | parser.add_argument('-P', '--parallel', 46 | type=int, 47 | default=0, 48 | help='Specify the parallelism for batch_run, default is "0".') 49 | parser.add_argument('-t', '--timeout', 50 | type=int, 51 | default=20, 52 | help='Specify the timeout for batch_run, default is "20".') 53 | parser.add_argument('-i', '--host_info_json', 54 | default=str(config.db_path) + '/host_info/host_info.json', 55 | help='Specify host info file to collect host static information, default is "' + str(config.db_path) + '/host_info/host_info.json".') 56 | parser.add_argument('-o', '--output_dir', 57 | default=str(config.db_path) + '/host_stat', 58 | help='Specify host info output directory, default is "' + str(config.db_path) + '/host_stat".') 59 | 60 | args = parser.parse_args() 61 | 62 | # Check and update output_dir. 63 | if os.path.exists(args.output_dir): 64 | args.output_dir = os.path.realpath(args.output_dir) 65 | else: 66 | common.bprint('"' + str(args.output_dir) + '": No such directory.', level='Error') 67 | sys.exit(1) 68 | 69 | return args.hosts, args.groups, args.user, args.password, args.parallel, args.timeout, args.host_info_json, args.output_dir 70 | 71 | 72 | class SampleHostStat(): 73 | def __init__(self, host_list, group_list, user, password, parallel, timeout, host_info_json, output_dir): 74 | self.host_list = host_list 75 | self.group_list = group_list 76 | self.user = user 77 | self.password = password 78 | self.parallel = parallel 79 | self.timeout = timeout 80 | self.host_info_json = host_info_json 81 | self.output_dir = output_dir 82 | 83 | self.top_host_stat_file = str(self.output_dir) + '/host_stat.json' 84 | current_date = datetime.datetime.now().strftime("%Y%m%d") 85 | current_time = datetime.datetime.now().strftime("%H%M%S") 86 | self.output_dir = str(self.output_dir) + '/' + str(current_date) + '/' + str(current_time) 87 | common.create_dir(self.output_dir) 88 | self.host_stat_file = str(self.output_dir) + '/host_stat.json' 89 | 90 | self.top_host_stat_file = str(config.db_path) + '/host_stat/host_stat.json' 91 | 92 | def get_batch_run_command(self, host_list=[], group_list=[], user='', password='', parallel=0, timeout=20): 93 | """ 94 | Get default batch_run command (without run command). 95 | """ 96 | batch_run_command = str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/bin/batch_run' 97 | 98 | if host_list: 99 | batch_run_command = str(batch_run_command) + ' --hosts ' + str(' '.join(host_list)) 100 | 101 | if group_list: 102 | batch_run_command = str(batch_run_command) + ' --groups ' + str(' '.join(group_list)) 103 | 104 | if user: 105 | batch_run_command = str(batch_run_command) + ' --user ' + str(user) 106 | 107 | if password: 108 | batch_run_command = str(batch_run_command) + ' --password ' + str(password) 109 | 110 | batch_run_command = str(batch_run_command) + ' --parallel ' + str(parallel) 111 | 112 | if timeout: 113 | batch_run_command = str(batch_run_command) + ' --timeout ' + str(timeout) 114 | 115 | return batch_run_command 116 | 117 | def collect_host_stat(self): 118 | """ 119 | Collect host stat information from free/top command output files under self.output_dir. 120 | "df --block-size GB /tmp" command output format: 121 | ---------------- 122 | Filesystem 1GB-blocks Used Available Use% Mounted on 123 | /dev/mapper/centos-tmp 1620GB 1GB 1620GB 1% /tmp 124 | ---------------- 125 | 126 | "free -g" command output format: 127 | ---------------- 128 | total used free shared buff/cache available 129 | Mem: 1007 85 18 0 903 919 130 | Swap: 127 12 115 131 | ---------------- 132 | 133 | "top" command output format: 134 | ---------------- 135 | top - 14:45:12 up 264 days, 2:54, 89 users, load average: 2.29, 3.15, 3.14 136 | Tasks: 1335 total, 1 running, 1330 sleeping, 0 stopped, 4 zombie 137 | %Cpu(s): 10.5 us, 4.0 sy, 0.0 ni, 84.4 id, 0.8 wa, 0.0 hi, 0.3 si, 0.0 st 138 | KiB Mem : 13289836+total, 954524 free, 10221516 used, 12172232+buff/cache 139 | KiB Swap: 8050684 total, 5294412 free, 2756272 used. 11724635+avail Mem 140 | 141 | PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 142 | 17706 root 20 0 174036 3884 1972 R 22.2 0.0 0:00.06 top -bc -n 1 143 | ---------------- 144 | """ 145 | host_stat_dic = {} 146 | 147 | # Get host_stat_dic based on *.stat files. 148 | tmp_compile = re.compile(r'^\s*(\S+)\s+(\d+)GB\s+(\d+)GB\s+(\d+)GB\s+(\d+)\%\s+/tmp\s*$$') 149 | mem_compile = re.compile(r'^\s*Mem:\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*$') 150 | swap_compile = re.compile(r'^\s*Swap:\s*(\d+)\s+(\d+)\s+(\d+)\s*$') 151 | top_compile = re.compile(r'^\s*top .* up\s*((\d+)\s*day(s)?,)?.* (\d+)\s+user(s)?,\s*load\s+average:\s*([0-9\.]+),\s*([0-9\.]+),\s*([0-9\.]+)\s*$') 152 | tasks_compile = re.compile(r'^\s*Tasks:\s*(\d+)\s*total,\s*(\d+)\s*running,\s*(\d+)\s*sleeping,\s*(\d+)\s*stopped,\s*(\d+)\s*zombie\s*$') 153 | cpu_compile = re.compile(r'^\s*%Cpu\(s\):\s*([0-9\.]+)\s*us,\s*([0-9\.]+)\s*sy,\s*([0-9\.]+)\s*ni,\s*([0-9\.]+)\s*id,\s*([0-9\.]+)\s*wa,\s*([0-9\.]+)\s*hi,\s*([0-9\.]+)\s*si,\s*([0-9\.]+)\s*st\s*$') 154 | 155 | # Get host host_name/groups info. 156 | host_info_dic = {} 157 | 158 | if os.path.exists(self.host_info_json): 159 | with open(self.host_info_json, 'r') as HIJ: 160 | host_info_dic = json.loads(HIJ.read()) 161 | 162 | # Parse host stat file(s). 163 | for root, dirs, files in os.walk(self.output_dir): 164 | for file in files: 165 | if re.match(r'^(\S+)\.stat$', file): 166 | my_match = re.match(r'^(\S+)\.stat$', file) 167 | host_ip = my_match.group(1) 168 | host_stat_dic.setdefault(host_ip, {'host_name': [], 169 | 'groups': [], 170 | 'up_days': 0, 171 | 'users': 0, 172 | 'tasks': 0, 173 | 'r1m': 0.0, 174 | 'r5m': 0.0, 175 | 'r15m': 0.0, 176 | 'cpu_thread': 0, 177 | 'cpu_id': 0.0, 178 | 'cpu_wa': 0.0, 179 | 'mem_total': 0, 180 | 'mem_used': 0, 181 | 'mem_free': 0, 182 | 'mem_shared': 0, 183 | 'mem_buff': 0, 184 | 'mem_avail': 0, 185 | 'swap_total': 0, 186 | 'swap_used': 0, 187 | 'swap_free': 0, 188 | 'tmp_total': 0, 189 | 'tmp_used': 0, 190 | 'tmp_avail': 0}) 191 | 192 | if host_ip in host_info_dic: 193 | if 'host_name' in host_info_dic[host_ip]: 194 | host_stat_dic[host_ip]['host_name'] = host_info_dic[host_ip]['host_name'] 195 | 196 | if 'groups' in host_info_dic[host_ip]: 197 | host_stat_dic[host_ip]['groups'] = host_info_dic[host_ip]['groups'] 198 | 199 | if 'cpu_thread' in host_info_dic[host_ip]: 200 | host_stat_dic[host_ip]['cpu_thread'] = host_info_dic[host_ip]['cpu_thread'] 201 | 202 | with open(os.path.join(root, file), 'r') as IF: 203 | for line in IF.readlines(): 204 | if tmp_compile.match(line): 205 | my_match = tmp_compile.match(line) 206 | host_stat_dic[host_ip]['tmp_total'] = int(my_match.group(2)) 207 | host_stat_dic[host_ip]['tmp_used'] = int(my_match.group(3)) 208 | host_stat_dic[host_ip]['tmp_avail'] = int(my_match.group(4)) 209 | elif mem_compile.match(line): 210 | my_match = mem_compile.match(line) 211 | host_stat_dic[host_ip]['mem_total'] = int(my_match.group(1)) 212 | host_stat_dic[host_ip]['mem_used'] = int(my_match.group(2)) 213 | host_stat_dic[host_ip]['mem_free'] = int(my_match.group(3)) 214 | host_stat_dic[host_ip]['mem_shared'] = int(my_match.group(4)) 215 | host_stat_dic[host_ip]['mem_buff'] = int(my_match.group(5)) 216 | host_stat_dic[host_ip]['mem_avail'] = int(my_match.group(6)) 217 | elif swap_compile.match(line): 218 | my_match = swap_compile.match(line) 219 | host_stat_dic[host_ip]['swap_total'] = int(my_match.group(1)) 220 | host_stat_dic[host_ip]['swap_used'] = int(my_match.group(2)) 221 | host_stat_dic[host_ip]['swap_free'] = int(my_match.group(3)) 222 | elif top_compile.match(line): 223 | my_match = top_compile.match(line) 224 | 225 | if my_match.group(1): 226 | host_stat_dic[host_ip]['up_days'] = int(my_match.group(2)) 227 | 228 | host_stat_dic[host_ip]['users'] = int(my_match.group(4)) 229 | host_stat_dic[host_ip]['r1m'] = float(my_match.group(6)) 230 | host_stat_dic[host_ip]['r5m'] = float(my_match.group(7)) 231 | host_stat_dic[host_ip]['r15m'] = float(my_match.group(8)) 232 | elif tasks_compile.match(line): 233 | my_match = tasks_compile.match(line) 234 | host_stat_dic[host_ip]['tasks'] = int(my_match.group(1)) 235 | elif cpu_compile.match(line): 236 | my_match = cpu_compile.match(line) 237 | host_stat_dic[host_ip]['cpu_id'] = float(my_match.group(4)) 238 | host_stat_dic[host_ip]['cpu_wa'] = float(my_match.group(5)) 239 | break 240 | 241 | return host_stat_dic 242 | 243 | def sample_host_stat_info(self, host_list, group_list): 244 | common.bprint('>>> Sampling host stat information ...') 245 | sample_command = 'df --block-size GB /tmp; free -g; top -b -n 1 | head -n 3' 246 | batch_run_command = self.get_batch_run_command(host_list, group_list, self.user, self.password, self.parallel, self.timeout) 247 | command = str(batch_run_command) + ' --command "' + str(sample_command) + '" --output_message_level 1 --output_file ' + str(self.output_dir) + '/HOST.stat' 248 | common.bprint(command, indent=4) 249 | os.system(command) 250 | 251 | def get_host_stat(self): 252 | common.bprint('\n>>> Collecting host stat ...') 253 | host_stat_dic = self.collect_host_stat() 254 | 255 | with open(self.host_stat_file, 'w') as HIF: 256 | HIF.write(str(json.dumps(host_stat_dic, ensure_ascii=False, indent=4)) + '\n') 257 | 258 | common.bprint(' Host info has been saved to file "' + str(self.host_stat_file) + '".') 259 | 260 | return host_stat_dic 261 | 262 | def gen_ssh_fail_host_file(self, host_stat_dic, ssh_fail_host_file): 263 | ssh_fail_host_list = [] 264 | 265 | for host_ip in host_stat_dic.keys(): 266 | if host_stat_dic[host_ip]['users'] == 0: 267 | ssh_fail_host_list.append(host_ip) 268 | 269 | if ssh_fail_host_list: 270 | with open(ssh_fail_host_file, 'w') as SFHF: 271 | for host_ip in ssh_fail_host_list: 272 | SFHF.write(str(host_ip) + '\n') 273 | 274 | def gen_overload_host_file(self, host_stat_dic, overload_host_file): 275 | overload_host_list = [] 276 | 277 | for host_ip in host_stat_dic.keys(): 278 | if ('cpu_thread' in host_stat_dic[host_ip]) and host_stat_dic[host_ip]['cpu_thread'] and (host_stat_dic[host_ip]['r1m'] >= host_stat_dic[host_ip]['cpu_thread']): 279 | overload_host_list.append(host_ip) 280 | 281 | if overload_host_list: 282 | with open(overload_host_file, 'w') as OHF: 283 | for host_ip in overload_host_list: 284 | OHF.write(str(host_ip) + '\n') 285 | 286 | def sample_host_top_info(self, host_list, group_list): 287 | common.bprint('\n>>> Sampling overload host top information ...') 288 | sample_command = 'top -bc -n 1 -w 256' 289 | batch_run_command = self.get_batch_run_command(host_list, group_list, self.user, self.password, self.parallel, self.timeout) 290 | command = str(batch_run_command) + ' --command "' + str(sample_command) + '" --output_message_level 1 --output_file ' + str(self.output_dir) + '/HOST.top' 291 | common.bprint(command, indent=4) 292 | os.system(command) 293 | 294 | def link_host_stat_json(self): 295 | common.bprint('\n>>> Link host_stat.json to top directory ...') 296 | 297 | if os.path.exists(self.host_stat_file): 298 | if os.path.lexists(self.top_host_stat_file): 299 | try: 300 | os.remove(self.top_host_stat_file) 301 | except Exception as error: 302 | common.bprint('Failed on removing file "' + str(self.top_host_stat_file) + '": ' + str(error), level='Error') 303 | 304 | try: 305 | common.bprint(' Link "' + str(self.host_stat_file) + '" into "' + str(self.top_host_stat_file)) 306 | os.symlink(self.host_stat_file, self.top_host_stat_file) 307 | except Exception as error: 308 | common.bprint('Failed on linking file "' + str(self.host_stat_file) + '" into "' + str(self.top_host_stat_file) + '": ' + str(error), level='Error') 309 | 310 | def cleanup(self): 311 | common.bprint('\n>>> Cleaning up .stat files ...') 312 | os.system('rm -f ' + str(self.output_dir) + '/*.stat') 313 | 314 | def sample_host_stat(self): 315 | # Sample host stat information. 316 | self.sample_host_stat_info(self.host_list, self.group_list) 317 | 318 | # Collect host stat. 319 | host_stat_dic = self.get_host_stat() 320 | 321 | # Re-sample host stat information for ssh fail host(s). 322 | ssh_fail_host_file = str(self.output_dir) + '/ssh_fail_host.list' 323 | self.gen_ssh_fail_host_file(host_stat_dic, ssh_fail_host_file) 324 | 325 | # Collect top information for overload host(s). 326 | overload_host_file = str(self.output_dir) + '/overload_host.list' 327 | self.gen_overload_host_file(host_stat_dic, overload_host_file) 328 | 329 | if os.path.exists(overload_host_file) and (os.path.getsize(overload_host_file) > 0): 330 | self.sample_host_top_info([overload_host_file, ], []) 331 | 332 | # Link host_stat.json into top directory. 333 | self.link_host_stat_json() 334 | 335 | # Clean up .stat info file if the r1m is less than specified value. 336 | self.cleanup() 337 | 338 | 339 | ################ 340 | # Main Process # 341 | ################ 342 | def main(): 343 | (hosts, groups, user, password, parallel, timeout, host_info_json, output_dir) = read_args() 344 | my_sample_host_stat = SampleHostStat(hosts, groups, user, password, parallel, timeout, host_info_json, output_dir) 345 | my_sample_host_stat.sample_host_stat() 346 | 347 | 348 | if __name__ == '__main__': 349 | main() 350 | -------------------------------------------------------------------------------- /tools/save_password.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ################################ 3 | # File Name : save_password.py 4 | # Author : liyanqing 5 | # Created On : 2021-08-16 20:11:25 6 | # Description : 7 | ################################ 8 | import os 9 | import sys 10 | import getpass 11 | import argparse 12 | 13 | sys.path.append(os.environ['BATCH_RUN_INSTALL_PATH']) 14 | from common import common_secure 15 | from config import config 16 | 17 | USER = getpass.getuser() 18 | os.environ['PYTHONUNBUFFERED'] = '1' 19 | 20 | 21 | def read_args(): 22 | """ 23 | Read in arguments. 24 | """ 25 | parser = argparse.ArgumentParser() 26 | 27 | parser.add_argument('-p', '--password', 28 | required=True, 29 | help='Specify user password.') 30 | parser.add_argument('-H', '--host', 31 | default='default', 32 | help='Specify the host which user password works on, default is "default".') 33 | parser.add_argument('-o', '--output_file', 34 | default='', 35 | help='Specify the output file, default is "/password/".') 36 | 37 | args = parser.parse_args() 38 | 39 | if not args.output_file: 40 | args.output_file = str(config.db_path) + '/password/' + str(USER) 41 | 42 | password_dir_path = os.path.dirname(args.output_file) 43 | 44 | if not os.path.exists(password_dir_path): 45 | try: 46 | os.makedirs(password_dir_path) 47 | os.chmod(password_dir_path, 0o1777) 48 | except Exception as error: 49 | print('*Error*: Failed on creating password directory "' + str(password_dir_path) + '", ' + str(error)) 50 | sys.exit(1) 51 | 52 | return (args.password, args.host, args.output_file) 53 | 54 | 55 | ################ 56 | # Main Process # 57 | ################ 58 | def main(): 59 | (password, host, output_file) = read_args() 60 | my_save_and_get_password = common_secure.SaveAndGetPassword() 61 | my_save_and_get_password.save_password(output_file, password, USER, host) 62 | 63 | 64 | if __name__ == '__main__': 65 | main() 66 | -------------------------------------------------------------------------------- /tools/show_top_file.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ################################ 3 | # File Name : show_top_file.py 4 | # Author : liyanqing.1987 5 | # Created On : 2024-12-20 16:42:24 6 | # Description : 7 | ################################ 8 | import os 9 | import re 10 | import sys 11 | import argparse 12 | 13 | from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QFrame, QGridLayout, QTableWidget, QTableWidgetItem, QHeaderView 14 | from PyQt5.QtCore import Qt 15 | 16 | sys.path.insert(0, str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/common') 17 | import common_pyqt5 18 | 19 | os.environ['PYTHONUNBUFFERED'] = '1' 20 | 21 | 22 | def read_args(): 23 | """ 24 | Read in arguments. 25 | """ 26 | parser = argparse.ArgumentParser() 27 | 28 | parser.add_argument('-f', '--top_file', 29 | required=True, 30 | default='', 31 | help='Specify top file path.') 32 | 33 | args = parser.parse_args() 34 | 35 | return args.top_file 36 | 37 | 38 | class ShowTopFile(QMainWindow): 39 | def __init__(self, top_file): 40 | super().__init__() 41 | self.top_file = top_file 42 | self.init_ui() 43 | 44 | def init_ui(self): 45 | # Add main_tab 46 | self.main_tab = QTabWidget(self) 47 | self.setCentralWidget(self.main_tab) 48 | 49 | self.main_frame = QFrame(self.main_tab) 50 | 51 | # Grid 52 | main_grid = QGridLayout() 53 | main_grid.addWidget(self.main_frame, 0, 0) 54 | self.main_tab.setLayout(main_grid) 55 | 56 | # Generate main_table 57 | self.gen_main_frame() 58 | 59 | # Show main window 60 | self.setWindowTitle(self.top_file) 61 | 62 | common_pyqt5.auto_resize(self, 1200, 600) 63 | common_pyqt5.center_window(self) 64 | 65 | def gen_main_frame(self): 66 | self.main_table = QTableWidget(self.main_frame) 67 | 68 | # Grid 69 | main_frame_grid = QGridLayout() 70 | main_frame_grid.addWidget(self.main_table, 0, 0) 71 | self.main_frame.setLayout(main_frame_grid) 72 | 73 | self.gen_main_table() 74 | 75 | def parse_top_file(self): 76 | """ 77 | Parse top_file and return top_line_list. 78 | 'top -bc -n 1' output message format: 79 | ---------------- 80 | top - 19:05:54 up 268 days, 7:15, 98 users, load average: 2.99, 3.02, 3.28 81 | Tasks: 1334 total, 1 running, 1329 sleeping, 0 stopped, 4 zombie 82 | %Cpu(s): 7.1 us, 1.6 sy, 0.0 ni, 91.3 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st 83 | KiB Mem : 13289836+total, 5669876 free, 11326056 used, 11590243+buff/cache 84 | KiB Swap: 8050684 total, 4564524 free, 3486160 used. 11681983+avail Mem 85 | 86 | PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 87 | 66159 root 20 0 174036 3896 1972 R 15.8 0.0 0:00.08 top -bc -n 1 88 | 14 root 20 0 0 0 0 S 5.3 0.0 11:47.34 [ksoftirqd/1] 89 | 123575 root 20 0 648644 28684 3364 S 5.3 0.0 210:35.80 /usr/libexec/gsd-color 90 | ---------------- 91 | """ 92 | top_dic_list = [] 93 | pid_compile = re.compile(r'^\s*PID\s+USER\s+.*COMMAND\s*$') 94 | line_compile = re.compile(r'\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+?)\s+') 95 | 96 | with open(self.top_file, 'r') as TF: 97 | mark = False 98 | 99 | for line in TF.readlines(): 100 | if mark and line_compile.match(line): 101 | my_match = line_compile.match(line) 102 | pid = int(my_match.group(1)) 103 | user = my_match.group(2) 104 | pr = my_match.group(3) 105 | ni = int(my_match.group(4)) 106 | virt = my_match.group(5) 107 | res = my_match.group(6) 108 | shr = my_match.group(7) 109 | s = my_match.group(8) 110 | cpu = float(my_match.group(9)) 111 | mem = float(my_match.group(10)) 112 | time = my_match.group(11) 113 | command = my_match.group(12) 114 | top_dic = {'pid': pid, 'user': user, 'pr': pr, 'ni': ni, 'virt': virt, 'res': res, 'shr': shr, 's': s, 'cpu': cpu, 'mem': mem, 'time': time, 'command': command} 115 | top_dic_list.append(top_dic) 116 | elif pid_compile.match(line): 117 | mark = True 118 | 119 | return top_dic_list 120 | 121 | def gen_main_table(self): 122 | self.main_table.setShowGrid(True) 123 | self.main_table.setSortingEnabled(True) 124 | self.main_table.setColumnCount(12) 125 | self.main_table.setHorizontalHeaderLabels(['PID', 'USER', 'PR', 'NI', 'VIRT', 'RES', 'SHR', 'S', '%CPU', '%MEM', 'TIME+', 'COMMAND']) 126 | 127 | # Set column width 128 | self.main_table.setColumnWidth(0, 60) 129 | self.main_table.setColumnWidth(1, 80) 130 | self.main_table.setColumnWidth(2, 40) 131 | self.main_table.setColumnWidth(3, 40) 132 | self.main_table.setColumnWidth(4, 80) 133 | self.main_table.setColumnWidth(5, 80) 134 | self.main_table.setColumnWidth(6, 80) 135 | self.main_table.setColumnWidth(7, 30) 136 | self.main_table.setColumnWidth(8, 60) 137 | self.main_table.setColumnWidth(9, 60) 138 | self.main_table.setColumnWidth(10, 90) 139 | self.main_table.horizontalHeader().setSectionResizeMode(11, QHeaderView.Stretch) 140 | 141 | # Set item 142 | top_dic_list = self.parse_top_file() 143 | self.main_table.setRowCount(len(top_dic_list)) 144 | 145 | i = -1 146 | 147 | for top_dic in top_dic_list: 148 | i += 1 149 | 150 | # Fill "PID" item. 151 | j = 0 152 | item = QTableWidgetItem() 153 | item.setData(Qt.DisplayRole, top_dic['pid']) 154 | self.main_table.setItem(i, j, item) 155 | 156 | # Fill "USER" item. 157 | j += 1 158 | item = QTableWidgetItem(top_dic['user']) 159 | self.main_table.setItem(i, j, item) 160 | 161 | # Fill "PR" item. 162 | j += 1 163 | item = QTableWidgetItem(top_dic['pr']) 164 | self.main_table.setItem(i, j, item) 165 | 166 | # Fill "NI" item. 167 | j += 1 168 | item = QTableWidgetItem() 169 | item.setData(Qt.DisplayRole, top_dic['ni']) 170 | self.main_table.setItem(i, j, item) 171 | 172 | # Fill "VIRT" item. 173 | j += 1 174 | item = QTableWidgetItem(top_dic['virt']) 175 | self.main_table.setItem(i, j, item) 176 | 177 | # Fill "RES" item. 178 | j += 1 179 | item = QTableWidgetItem(top_dic['res']) 180 | self.main_table.setItem(i, j, item) 181 | 182 | # Fill "SHR" item. 183 | j += 1 184 | item = QTableWidgetItem(top_dic['shr']) 185 | self.main_table.setItem(i, j, item) 186 | 187 | # Fill "S" item. 188 | j += 1 189 | item = QTableWidgetItem(top_dic['s']) 190 | self.main_table.setItem(i, j, item) 191 | 192 | # Fill "%CPU" item. 193 | j += 1 194 | item = QTableWidgetItem() 195 | item.setData(Qt.DisplayRole, top_dic['cpu']) 196 | self.main_table.setItem(i, j, item) 197 | 198 | # Fill "%MEM" item. 199 | j += 1 200 | item = QTableWidgetItem() 201 | item.setData(Qt.DisplayRole, top_dic['mem']) 202 | self.main_table.setItem(i, j, item) 203 | 204 | # Fill "TIME+" item. 205 | j += 1 206 | item = QTableWidgetItem(top_dic['time']) 207 | self.main_table.setItem(i, j, item) 208 | 209 | # Fill "COMMAND" item. 210 | j += 1 211 | item = QTableWidgetItem(top_dic['command']) 212 | self.main_table.setItem(i, j, item) 213 | 214 | 215 | ################ 216 | # Main Process # 217 | ################ 218 | def main(): 219 | top_file = read_args() 220 | app = QApplication(sys.argv) 221 | my_show = ShowTopFile(top_file) 222 | my_show.show() 223 | sys.exit(app.exec_()) 224 | 225 | 226 | if __name__ == '__main__': 227 | main() 228 | -------------------------------------------------------------------------------- /tools/switch_etc_hosts.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ################################ 3 | # File Name : switch_etc_hosts.py 4 | # Author : liyanqing.1987 5 | # Created On : 2023-07-14 15:12:43 6 | # Description : 7 | ################################ 8 | import os 9 | import re 10 | import sys 11 | import copy 12 | import argparse 13 | 14 | sys.path.append(str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/config') 15 | import config 16 | 17 | sys.path.insert(0, os.environ['BATCH_RUN_INSTALL_PATH']) 18 | from common import common 19 | 20 | os.environ['PYTHONUNBUFFERED'] = '1' 21 | 22 | 23 | def read_args(): 24 | """ 25 | Read in arguments. 26 | """ 27 | parser = argparse.ArgumentParser() 28 | 29 | parser.add_argument('-i', '--input_file', 30 | default='/etc/hosts', 31 | help='Specify input file, default is "/etc/hosts".') 32 | parser.add_argument('-o', '--output_file', 33 | default=str(config.host_list), 34 | help='Specify output file, default is "' + str(config.host_list) + '".') 35 | parser.add_argument('-a', '--append', 36 | default='', 37 | help='Append configuration file into output file.') 38 | parser.add_argument('-eh', '--expected_hosts', 39 | nargs='+', 40 | default=[], 41 | help='Specify expected ip(s), support regular expressions.') 42 | parser.add_argument('-eg', '--expected_groups', 43 | nargs='+', 44 | default=[], 45 | help='Specify expected group(s), support regular expressions.') 46 | parser.add_argument('-EH', '--excluded_hosts', 47 | nargs='+', 48 | default=[], 49 | help='Specify excluded ip(s), support regular expressions.') 50 | parser.add_argument('-EG', '--excluded_groups', 51 | nargs='+', 52 | default=[], 53 | help='Specify excluded group(s), support regular expressions.') 54 | parser.add_argument('-r', '--rewrite', 55 | action='store_true', 56 | default=False, 57 | help='Rewrite mode, rewrite output file by force.') 58 | parser.add_argument('-t', '--tool', 59 | default='batchRun', 60 | choices=['batchRun', 'ansible'], 61 | help='Which tool the host list is for, default is "batchRun".') 62 | 63 | args = parser.parse_args() 64 | 65 | # input_file must exists. 66 | if not os.path.exists(args.input_file): 67 | common.bprint('"' + str(args.input_file) + '": No such input file.', level='Error') 68 | sys.exit(1) 69 | 70 | # Will exit if output_file exists without rewrite mode. 71 | if os.path.exists(args.output_file) and (not args.rewrite): 72 | common.bprint('Output file "' + str(args.output_file) + '" exists, please remote it, or enable rewrite mode.', level='Error') 73 | sys.exit(1) 74 | 75 | # Check append file exists or not. 76 | if args.append and (not os.path.exists(args.append)): 77 | args.append = '' 78 | 79 | return (args.input_file, args.output_file, args.append, args.expected_hosts, args.expected_groups, args.excluded_hosts, args.excluded_groups, args.tool) 80 | 81 | 82 | class SwitchEtcHosts(): 83 | """ 84 | Switch /etc/hosts (or similar) file into batchRun host.list file. 85 | """ 86 | def __init__(self, input_file, output_file, append_file, expected_host_list, expected_group_list, excluded_host_list, excluded_group_list, tool): 87 | self.input_file = input_file 88 | self.output_file = output_file 89 | self.append_file = append_file 90 | self.expected_host_list = expected_host_list 91 | self.expected_group_list = expected_group_list 92 | self.excluded_host_list = excluded_host_list 93 | self.excluded_group_list = excluded_group_list 94 | self.tool = tool 95 | 96 | def parse_input_file(self): 97 | """ 98 | input_file must match below format. 99 | # GROUP : 100 | 101 | # SSH_PORT= 102 | """ 103 | input_dic = {} 104 | group = '' 105 | 106 | with open(self.input_file, 'r') as IF: 107 | for line in IF.readlines(): 108 | line = line.strip() 109 | 110 | if re.match(r'^\s*$', line): 111 | continue 112 | elif re.match(r'^\s*#.*$', line): 113 | if re.match(r'^\s*#\s*GROUP\s*:\s*(\S+).*$', line): 114 | my_match = re.match(r'^\s*#\s*GROUP\s*:\s*(\S+).*$', line) 115 | group = my_match.group(1) 116 | 117 | if group in input_dic: 118 | common.bprint('Group "' + str(group) + '" is defined repeatedly.', level='Error') 119 | sys.exit(1) 120 | else: 121 | input_dic[group] = {} 122 | else: 123 | common.bprint('Comment line, igonre', level='Warning') 124 | common.bprint(line, color=33, display_method=1, indent=11) 125 | elif re.match(r'^\s*((([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5])\.){3}([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5]))\s+(.+?)\s*(#.*?)?\s*$', line): 126 | my_match = re.match(r'^\s*((([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5])\.){3}([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5]))\s+(.+?)\s*(#.*?)?\s*$', line) 127 | host_ip = my_match.group(1) 128 | host_names_string = my_match.group(5) 129 | comment_string = my_match.group(6) 130 | ssh_port = '' 131 | 132 | if comment_string and re.match(r'^#\s*SSH_PORT\s*=\s*(\d+)$', comment_string): 133 | my_match = re.match(r'^#\s*SSH_PORT\s*=\s*(\d+)$', comment_string) 134 | ssh_port = my_match.group(1) 135 | 136 | if not group: 137 | common.bprint('Group missing for below line, igonre', level='Warning') 138 | common.bprint(line, color=33, display_method=1, indent=11) 139 | else: 140 | # Save host_ip into input_dic. 141 | input_dic[group].setdefault(host_ip, {}) 142 | input_dic[group][host_ip].setdefault('host_name', []) 143 | 144 | for host_name in host_names_string.split(): 145 | if host_name not in input_dic[group][host_ip]['host_name']: 146 | input_dic[group][host_ip]['host_name'].append(host_name) 147 | 148 | if ssh_port: 149 | input_dic[group][host_ip].setdefault('ssh_port', ssh_port) 150 | else: 151 | common.bprint('Meaningless line, igonre', level='Warning') 152 | common.bprint(line, color=33, display_method=1, indent=11) 153 | 154 | return input_dic 155 | 156 | def filter_input_dic(self, input_dic): 157 | """ 158 | Filter input_dic with self.expected_host_list/self.expected_group_list/self.excluded_host_list/self.excluded_group_list. 159 | """ 160 | filtered_input_dic = {} 161 | 162 | # Fill with self.expected_group_list: 163 | for group in input_dic.keys(): 164 | if (not self.expected_group_list) or (group in self.expected_group_list) or self.fuzzy_match_in(group, self.expected_group_list): 165 | filtered_input_dic[group] = input_dic[group] 166 | 167 | # Filter with self.excluded_group_list: 168 | if self.excluded_group_list: 169 | group_list = list(filtered_input_dic.keys()) 170 | 171 | for group in group_list: 172 | if (group in self.excluded_group_list) or self.fuzzy_match_in(group, self.excluded_group_list): 173 | del filtered_input_dic[group] 174 | 175 | # Filter with self.expected_host_list: 176 | if self.expected_host_list: 177 | for group in filtered_input_dic.keys(): 178 | group_dic = copy.deepcopy(filtered_input_dic[group]) 179 | 180 | for host in group_dic.keys(): 181 | if (host not in self.expected_host_list) and (not self.fuzzy_match_in(host, self.expected_host_list)): 182 | del filtered_input_dic[group][host] 183 | 184 | # Filter with self.excluded_host_list: 185 | if self.excluded_host_list: 186 | for group in filtered_input_dic.keys(): 187 | group_dic = copy.deepcopy(filtered_input_dic[group]) 188 | 189 | for host in group_dic.keys(): 190 | if (host in self.excluded_host_list) or self.fuzzy_match_in(host, self.excluded_host_list): 191 | del filtered_input_dic[group][host] 192 | 193 | return filtered_input_dic 194 | 195 | def fuzzy_match_in(self, specified_item, fuzzy_item_list): 196 | """ 197 | If there is a fuzzy match between specified_item and any item in fuzzy_item_list, return True; otherwise, return False. 198 | """ 199 | try: 200 | for fuzzy_item in fuzzy_item_list: 201 | if re.match(fuzzy_item, specified_item): 202 | return True 203 | except Exception as error: 204 | common.bprint('Failed on fuzzy matching "' + str(specified_item) + '" with "' + str(fuzzy_item_list) + '".', level='Error') 205 | common.bprint(error, color=31, display_method=1, indent=9) 206 | 207 | return False 208 | 209 | def write_output_file(self, input_dic): 210 | """ 211 | Write output_file as batchRun host.list format. 212 | """ 213 | if input_dic: 214 | with open(self.output_file, 'w') as OF: 215 | for group in input_dic.keys(): 216 | if input_dic[group]: 217 | OF.write('\n[' + str(group) + ']\n') 218 | 219 | for host_ip in input_dic[group].keys(): 220 | for host_name in input_dic[group][host_ip]['host_name']: 221 | if self.tool == 'batchRun': 222 | if 'ssh_port' in input_dic[group][host_ip]: 223 | OF.write(str(host_ip) + ' ssh_host=' + str(host_name) + ' ssh_port=' + str(input_dic[group][host_ip]['ssh_port']) + '\n') 224 | else: 225 | OF.write(str(host_ip) + ' ssh_host=' + str(host_name) + '\n') 226 | elif self.tool == 'ansible': 227 | if 'ssh_port' in input_dic[group][host_ip]: 228 | OF.write(str(host_ip) + ' ansible_ssh_host=' + str(host_name) + ' ansible_ssh_port=' + str(input_dic[group][host_ip]['ssh_port']) + '\n') 229 | else: 230 | OF.write(str(host_ip) + ' ansible_ssh_host=' + str(host_name) + '\n') 231 | 232 | if self.append_file: 233 | with open(self.append_file, 'r') as AF: 234 | for line in AF.readlines(): 235 | OF.write(str(line).strip() + '\n') 236 | 237 | common.bprint('') 238 | common.bprint('Output File : ' + str(self.output_file)) 239 | 240 | def run(self): 241 | input_dic = self.parse_input_file() 242 | input_dic = self.filter_input_dic(input_dic) 243 | self.write_output_file(input_dic) 244 | 245 | 246 | ################ 247 | # Main Process # 248 | ################ 249 | def main(): 250 | (input_file, output_file, append_file, expected_host_list, expected_group_list, excluded_host_list, excluded_group_list, tool) = read_args() 251 | my_switch_etc_hosts = SwitchEtcHosts(input_file, output_file, append_file, expected_host_list, expected_group_list, excluded_host_list, excluded_group_list, tool) 252 | my_switch_etc_hosts.run() 253 | 254 | 255 | if __name__ == '__main__': 256 | main() 257 | --------------------------------------------------------------------------------