forked from ytsarev/suseviclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
suseviclient.sh
executable file
·1416 lines (1160 loc) · 46 KB
/
suseviclient.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash -
#===============================================================================
#
# FILE: suseviclient.sh
#
# USAGE: ./suseviclient.sh <options>
#
# DESCRIPTION: Lightweight VMware ESXi management tool
#
# OPTIONS: see ./suseviclient.sh --help
# REQUIREMENTS: bash,ssh and vncviewer
# BUGS: ---
# NOTES: ---
# AUTHOR: Yury Tsarev, [email protected]
# COMPANY: SUSE
#===============================================================================
#set -o nounset # Treat unset variables as an error
#kinda config section
[ -f ~/.suseviclientrc ] && . ~/.suseviclientrc
# end of config section
# setting SSH Control Master
control_master() {
CONTROL=/tmp/ssh-control-`date +%s`-$RANDOM
ssh -NfM -S $CONTROL root@$esx_server || exit
MASTERPID=`ps -aef | grep "ssh -NfM -S $CONTROL" | grep -v grep | awk {'print $2'}`
ssh="ssh -S $CONTROL"
scp="scp -o ControlPath=\"$CONTROL\""
}
cleanup() {
[ ! -z $MASTERPID ] && kill $MASTERPID
if [ -n "$1" ];then
exit $1
else
exit 0
fi
}
#generic helpers
yesno (){
if [ -n "$globalyes" ]; then
return 0
fi
while true
do
echo "$*"
echo "Please answer by entering (y)es or (n)o:"
read ANSWER
case "$ANSWER" in
[yY] | [yY][eE][sS] )
return 0
;;
[nN] | [nN][oO] )
return 1
;;
* )
echo "I cannot understand you over here."
;;
esac
done
}
strip_chars() {
echo "${1//[\'\"\,\!\@\#\$\%\^\&\*\(\)\/\?\[\]\:\>\<\{\}\|\\\'\;]/}"
}
#studio
rdom () { local IFS=\> ; read -d \< E C ;}
appliances() {
tempfile=/tmp/applist-`date +%s`-$RANDOM
curl -s -u "$1":"$2" "http://$studioserver/api/v1/user/appliances" > $tempfile
if [[ $? != 0 ]];then echo "Can't connect to specified studio server";rm -f $tempfile; exit; fi
while rdom; do
if [[ $E = id ]]; then
if [[ -z $flag ]]; then
echo "ApplianceID: "$C
flag=1
else
#echo "ParentID:"$C
unset flag
fi
fi
if [[ $E = build ]]; then
flag=1
fi
if [[ $E = name ]]; then
if [[ -z $nflag ]]; then
echo "Appliance Name: "$C
nflag=1
else
echo "System template: "$C
unset nflag
fi
fi
if [[ $E = appliance ]]; then
echo -e "---------------"
fi
if [[ $E = arch ]]; then
echo "Architecture: "$C
fi
if [[ $E = edit_url ]]; then
echo "URL: "$C
fi
if [[ $E = estimated_raw_size ]]; then
echo "Size: "$C
fi
if [[ $E = estimated_compressed_size ]]; then
echo "Compressed size: "$C
fi
if [[ $E = message ]]; then
echo $C
fi
done < $tempfile
rm -f $tempfile
unset tempfile
}
buildimage() {
studio_before_filter
tempfile=/tmp/buildimage-`date +%s`-$RANDOM
curl -s -u "$1":"$2" -XPOST "http://$studioserver/api/v1/user/running_builds?appliance_id=$3&force=1&image_type=$format" > $tempfile
if [[ $? != 0 ]];then echo "Can't connect to specified studio server";rm -f $tempfile; exit; fi
while rdom; do
if [[ $E = id ]]; then
echo "Build started with id "$C
fi
if [[ $E = message ]]; then
echo $C
fi
done < $tempfile
rm $tempfile
unset tempfile
}
buildstatus() {
tempfile=/tmp/buildimage-`date +%s`-$RANDOM
curl -s -u "$1":"$2" "http://$studioserver/api/v1/user/running_builds?appliance_id=$3" > $tempfile
if [[ $? != 0 ]];then echo "Can't connect to specified studio server";rm -f $tempfile; exit; fi
while rdom; do
if [[ $E = id ]]; then
echo "Build id: "$C
fi
if [[ $E = state ]]; then
echo "State: "$C
fi
if [[ $E = percent ]]; then
echo "Percents done: "$C
fi
if [[ $E = time_elapsed ]]; then
echo "Time elapsed: $(( $C/60 )) minutes"
fi
if [[ $E = message ]]; then
echo "Current action: "$C
fi
done < $tempfile
rm $tempfile
unset tempfile
}
checkimage() {
tempfile=/tmp/checkimage-`date +%s`-$RANDOM
curl -s -u "$1":"$2" "http://$studioserver/api/v1/user/appliances/$3" > $tempfile
while rdom; do
if [[ $E = name && ! $nonameupdate -eq 1 ]];then
appliance_name="$C"
nonameupdate=1
fi
if [[ $E = arch ]]; then
arch="$C"
fi
if [[ $E = version ]]; then
version="$C"
fi
if [[ $E = image_type ]]; then
if [[ $C = "$format" ]]; then
type=$C
fi
fi
if [[ $E = download_url && $type = "$format" ]]; then
imagelink="$C"
unset type
#break loop to get latest image version
break
fi
done < $tempfile
rm $tempfile
unset tempfile
if [[ -z $imagelink ]]; then
echo "Image is not ready"; cleanup
else echo "Image is ready, we can upload it to server..."
fi
}
imageupload() {
#curl -u "$1":"$2" "$imagelink" | $ssh root@$esx_server "cat > /vmfs/volumes/$datastore/${name// /\ }/studio.iso" && echo "Image uploaded"
if [ "$format" = "oemiso" ] ; then
$ssh root@$esx_server "wget $imagelink -O /vmfs/volumes/$datastore/${name// /\ }/studio.iso"
if [ $? -eq 0 ]; then
echo "Image uploaded"
else
echo "Image upload failure :("; cleanup
fi
elif [ "$format" = "vmx" ] ; then
img_filename=$(basename $imagelink)
tarname=$(echo $img_filename| sed -n 's/\(.*\)\.vmx.tar.gz/\1.vmx.tar/p')
$ssh root@$esx_server "cd '/vmfs/volumes/$datastore/' && wget '$imagelink'"
if [ $? -eq 0 ]; then
echo "Image uploaded"
else
echo "Image upload failure :("; cleanup
fi
$ssh root@$esx_server "cd '/vmfs/volumes/$datastore/' && echo \"Unpacking image, please wait...\" && gunzip '$img_filename'"
realname=$($ssh root@$esx_server "cd '/vmfs/volumes/$datastore/' && tar -tf $tarname | sed -n 's/\///g;1p'")
realfilename=$($ssh root@$esx_server "cd '/vmfs/volumes/$datastore/' && tar -tf $tarname |sed -n 's/.*\/\(.*\)\.vmdk/\1/p'")
$ssh root@$esx_server "cd '/vmfs/volumes/$datastore/' && tar -xf $tarname && rm '$tarname' && mv '$realname' '$name' && chown root:root -R './$name' && cd './$name' && mv '$realfilename'.vmx '$name.vmx' && mv '$realfilename'.vmdk '$name.vmdk'" && echo "Image uploaded & unpacked"
fi
}
vmdk_convert ()
{
$ssh root@$esx_server "cd '/vmfs/volumes/$datastore/$1/' && mv './$1.vmdk' './$1.vmdk.preconvert' && vmkfstools -i '$1.vmdk.preconvert' -d thin '$1.vmdk' && rm '$1.vmdk.preconvert'"
} # ---------- end of function vmkd_convert ----------
vmx_convert ()
{
vnc_port
vnc_conf
pathtoconfig="/vmfs/volumes/$datastore/$name/$name.vmx"
$ssh root@$esx_server "sed -i 's/virtualHW.version = \"4\"/virtualHW.version = \"7\"/g; s/ide0:0.*//g; s/$realfilename/$name/g' '$pathtoconfig'"
echo -e "$vnc_config\nethernet0.networkName = \"VM Network\"" | $ssh root@$esx_server "cat >> '$pathtoconfig'"
} # ---------- end of function vmx_convert ----------
#vmware
initial_info() {
if [ -t 1 ] ; then
COL_GREEN="\033[32m"
COL_RED="\033[31m"
COL_OFF="\033[0m"
fi
echo -e "\nPowerstate\tVMID\tVM Label\t\t\t\tConfig file"
echo -e "----------\t----\t--------\t\t\t\t-----------"
allvms=`$ssh root@$esx_server "vim-cmd vmsvc/getallvms"`
tempfile=/tmp/vmlist-control-`date +%s`-$RANDOM
echo "$allvms" | sed '1d;s/\.vmx\s.*vmx-[0-9]*/\.vmx/g' | sort -n > $tempfile
while read line
do
#More straightforward solution but it's too slow:(
# lvmid=`echo $line | awk '/[0-9]/ {print $1}'`
# pwstate=`$ssh root@$esx_server "vim-cmd vmsvc/power.getstate $lvmid | tail -1" < /dev/null`
#Faster one
name=`echo $line | grep -o "\ [A-Za-z0-9].*\[" | sed 's/\s*\[//;s/^\s//'`
resolved_ds=$(echo $line| grep -o '\[.*\]' |egrep -o '[A-Za-z0-9-]+')
resolved_ds=$($ssh root@$esx_server "cd /vmfs/volumes/$resolved_ds;pwd -P"< /dev/null)
relpath=$(echo $line | sed -n 's/.*] \(.*\)\.vmx.*/\1.vmx/p')
$ssh root@$esx_server "/usr/lib/vmware/bin/vmdumper -l| grep \"$resolved_ds/$relpath\" > /dev/null" < /dev/null
pwstate=$?
if [ $pwstate -eq 0 ]
then
finallist=$finallist"${COL_GREEN}Powered on${COL_OFF} $line\n"
else
finallist=$finallist"${COL_RED}Powered off${COL_OFF} $line\n"
fi
done < $tempfile
finallist=`echo -n "$finallist"|sort`
echo -ne "$finallist"
rm $tempfile
}
usage() {
echo "
Tool to create and control virtual machines on ESXi servers
VM creation:
------------
-s <ip or domain name of ESX server>
-c Create new vm
-n <label> for the new virtual machine
-m <size> of RAM in megabytes. Can be omitted. Default is 512 MB
-d <size> of hard disk (M/G). Can be omitted. Default is 5 GB
--ds <datastore name> where VM will be created (optional)
--network <name> connect VM network adapter to specified virtual network(optional)
--mac <address> custom mac address for ethernet device. (must be started with 00:50:56)
--vncpass <password> set password to access vm console via vnc. Use this if you need non-interactive VM creation.
--novncpass omits setting vnc password so no authorization will be required
--iso <path> to ISO image in format of <datastore>/path/to/image.iso
--vmdk <path> to VMDK image in format of <datastore>/path/to/image.iso
--studio <appliance_id> Deploy appliance from SUSE Studio server, see studio options below
VM modification:
----------------
-e <vmid> <param to change> Edit existing VM. Available parameters for editing:
-n <label> Change label
--iso <path> Connect another iso image
--network <name> Switch to another virtual network
--vncpass <password> Change VNC passord
--vncpass -i interactively change password with checks
--novncpass remove password enabling connection without authentication
Cloning:
--------
--clone <vmid> Clone the specified VM. Can be extended with -n <label> and --ds <datastore> options
--toserver <esxi server> clone to *another* ESXi server. Do NOT use this option when cloning within one server
Exporting:
----------
--export <vmid> <local_directory> Export VM from ESXi to local desktop to use with VMWare desktop products(Workstation/Player)
Generic management:
-------------------
-l List all guests
--dslist List all datastores
--dsbrowse List files on specified datastore
--status <vmid> Get parametres of VM
--poweron <vmid> Power On VM
--bios Launch a VM's BIOS after start
--autoyast <network path> (http/ftp/nfs) to autoyast xml control file
--poweroff <vmid> Power Off VM
--reset <vmid> Reset VM
--vnc <vmid> Connect to VM via VNC
--showvncport <vmid> Print VNC port assigned to specified VM
--addvnc <vmid> Add VNC support to an existing VM ( guest need to be restarted to take effect)
--remove <vmid> Delete VM
Snapshot management:
--------------------
--snapshotlist <vmid> Get list of snapshots for current VM
--snapshot <vmid> --snapname <snapshot label> Make snapshot of current VM status
If --snapname is not specified the label will default to \"snapshot\$timestamp\"
--snapshotremove <vmid> --snapname <snapshot label> Remove a snapshot with specified name
--snapshotremove <vmid> --snapid <snapshot_id> Remove a snapshot with specified ID
--snapshotremove <vmid> --all Remove all snapshots for specidied VM
--revert <vmid> --snapname <snapshot label> Revert to snapshot by name
--revert <vmid> --snapid <snapshot id> Revert to snapshot by ID
SUSE Studio specific options:
-----------------------------
--studioserver <custom.server.com> Custom suse studio server ( if option is omitted susestudio.com is a default)
--apiuser <api_user> your SUSE Studio user (see http://susestudio.com/user/show_api_key )
--apikey <api_key> your SUSE Studio api key
--appliances Get appliance list from SUSE Studio
--buildimage <appliance_id> Build Preload ISO of specified appliance for deployment
--buildstatus <appliance_id> Get info on running builds of specified appliance
--format <image format> specify oemiso or vmx here
--help This help
Network Management:
-------------------
--networks <vmid> list networks used by VM
--vswitches list virtual switches
--nics list network adapters available on ESXi server
--vswitchadd <name> Create virtual switch with default corresponding network port group
--vswitchremove <name> Remove virtual switch
Configuration file:
--------------------
You can specify frequently used options in configuration file of ~/.suseviclientrc
Example of such a config file with comments:
#Default ESXi server to work with
esx_server=\"thessalonike.suse.de\"
#SUSE Studio API user
apiuser=\"studiouser\"
#SUSE Studio API key
apikey=\"studioapikey\"
#Custom SUSE Studio server
studioserver=\"istudio.suse.de\"
All specified directives in config file are easily overridable by the related command control option.
"
}
# Create and register VM
register_vm () {
if [[ ! -z $studio ]]; then
if [[ ! -z $apiuser && ! -z $apikey ]];then
[ $format = "oemiso" ] && $ssh root@$esx_server "mkdir \"/vmfs/volumes/$datastore/$name\"" && iso="$datastore/$name/studio.iso"
imageupload "$apiuser" "$apikey" ;
[ $format = "vmx" ] && vmdk_convert "$name" && vmx_convert && $ssh root@$esx_server "vim-cmd solo/registervm '/vmfs/volumes/$datastore/$name/$name.vmx'" && echo "Virtual machine \"$name\" created" && cleanup
else
echo "Please provide studio apiuser and apikey"; exit
fi
fi
config="
config.version = \"8\"
virtualHW.version= \"7\"
guestOS = \"sles11\"
memsize = \"$ram\"
displayname = \"$name\"
scsi0.present = \"TRUE\"
scsi0.virtualDev = \"lsilogic\"
scsi0:0.present = \"TRUE\"
scsi0:0.fileName = \"$name.vmdk\""
if [ -n "$iso" ];then
iso_config="
ide1:0.present = \"true\"
ide1:0.deviceType = \"cdrom-image\"
ide1:0.filename = \"/vmfs/volumes/$iso\"
ide1:0.startConnected = \"TRUE\""
else
iso_config=""
fi
network_config="
ethernet0.present= \"true\"
ethernet0.startConnected = \"true\"
ethernet0.virtualDev = \"e1000\"
ethernet0.networkName = \"$network_name\""
#extend network settings if custom mac address is specified
if [ -n "$mac" ];then
network_config="
$network_config
ethernet0.addressType=\"static\"
ethernet0.address = \"$mac\""
fi
$ssh root@$esx_server "[[ ! -d \"/vmfs/volumes/$datastore/$name\" ]] && mkdir \"/vmfs/volumes/$datastore/$name\""
echo "$config$iso_config$network_config$vnc_config" | $ssh root@$esx_server "cat > '/vmfs/volumes/$datastore/$name/$name.vmx'"
#Create an empty scsci disk of if vmdk specified copy it to the vm's dir
if [ -n "$vmdk" ];then
$ssh root@$esx_server "vmkfstools -i '/vmfs/volumes/$vmdk' -d thin '/vmfs/volumes/$datastore/$name/$name.vmdk'"
else
$ssh root@$esx_server "cd '/vmfs/volumes/$datastore/$name' && vmkfstools -c $disk -a lsilogic '$name.vmdk' "
fi
if [ $? -ne 0 ] ; then
echo "Virtual disk creation failure";
$ssh root@$esx_server "rm -rf '/vmfs/volumes/$datastore/$name/'"
cleanup
fi
$ssh root@$esx_server "vim-cmd solo/registervm '/vmfs/volumes/$datastore/$name/$name.vmx'"
if [ $? -eq 0 ] ; then
echo "Virtual machine \"$name\" created"
fi
}
# getting the vmid of current vm
get_vmid() {
vmid=$($ssh root@$esx_server "vim-cmd vmsvc/getallvms | grep '$name' | awk '{print \$1}'")
}
vmid2name(){
name=$($ssh root@$esx_server "vim-cmd vmsvc/get.summary $1 | grep name " | sed -n 's/name = "\(.*\)",/\1/p' | sed 's/^[ \t]*//;s/[ \t]*$//')
if [ -z "$name" ]; then
return 1
fi
}
vmid2datastore(){
datastore=$($ssh root@$esx_server "vim-cmd vmsvc/get.config $1 | grep vmPathName| grep -o '\"\[.*\]' |egrep -o '[A-Za-z0-9-]+'")
}
vmid2relpath(){
relpath=$($ssh root@$esx_server "vim-cmd vmsvc/get.config $1 | grep vmPathName | sed 's/.*] //g; s/\",.*//g'")
}
relpath2vmdkpath(){
#TODO:extend to the case of multiple disks
vmdkpath=$($ssh root@$esx_server "grep -i \.vmdk '/vmfs/volumes/$datastore/$relpath' | sed -n 's/.*\"\(.*\)\.vmdk.*/\1.vmdk/p' | head -1")
vmdkpath="$(dirname "$relpath")/$vmdkpath"
}
vnc_connect(){
vncpassword=""
passwd_counter=1
connect=1
while [ $connect ]; do
if [ $passwd_counter -gt 3 ];then
cleanup
fi
output=$(echo "$vncpassword"|vncviewer -autopass -encodings 'hextile zlib copyrect' $esx_server:$vnc_conn_port 2>&1)
echo $output| egrep -q "Performing standard VNC authentication"
if [[ $? -eq 0 && $vncpassword = "" ]];then
stty_orig=`stty -g`
stty -echo
echo "Enter VNC password:"
read vncpassword
stty $stty_orig
output="suseviclient-vncrestart"
passwd_counter=$(($passwd_counter+1))
fi
echo $output| egrep -q "(VNC connection failed|Unable to connect to VNC server)"
if [ $? -eq 0 ]; then
echo "VNC connection failed"
fi
echo $output| egrep -q "(Unknown message type|Zero size rect|suseviclient-vncrestart|Rect too large)"
if [ $? -eq 1 ]; then
connect=""
fi
done
}
vnc_port(){
tempfile=/tmp/dslist-`date +%s`-$RANDOM
$ssh root@$esx_server "vim-cmd vmsvc/getallvms| grep -o '\[.*\]' |egrep -o '[A-Za-z0-9-]+' |sort |uniq" > $tempfile
while read line
do
searchpath="${searchpath} /vmfs/volumes/$line/"
done < $tempfile
rm -f $tempfile
vnc_port=`$ssh root@$esx_server "find $searchpath -iname *.vmx -exec grep vnc\.port {} \;" | awk '{print $3}' | sed s/\"//g | sort | tail -1`
[ -z $vnc_port ] && vnc_port="5900"
((vnc_port++))
}
vnc_pass(){
if [ $no_vnc_password -eq 1 ]; then
vnc_password=""
return 0
fi
if [ -z "$vnc_password" ];then
stty_orig=`stty -g`
stty -echo
echo "Enter new VNC password:"
read vncp1
echo "Repeat VNC password:"
read vncp2
stty $stty_orig
if [ "$vncp1" = "$vncp2" ];
then echo "VNC passwords match."
vnc_password=$vncp2
else
echo "Passwords do not match"
vnc_pass
fi
fi
}
get_vnc_port(){
vnc_conn_port=`$ssh root@$esx_server "grep vnc\.port '/vmfs/volumes/$datastore/$relpath'" | awk '{print $3}' | sed s/\"//g`
if [ ! -z "$vnc_conn_port" ] ; then
return 0
else
echo "vnc is not enabled on this virtual machine. Please try --addvnc feature."; return 1
fi
}
power_on() {
if [ ! -z $bios_once ]
then
vmid2datastore $1
vmid2relpath $1
biosonce_config="bios.forceSetupOnce = \"TRUE\""
$ssh root@$esx_server "grep bios\.forceSetupOnce '/vmfs/volumes/$datastore/$relpath' && sed -i s/bios\.forceSetupOnce.*/bios\.forceSetupOnce=TRUE/g '/vmfs/volumes/$datastore/$relpath'" > /dev/null
$ssh root@$esx_server "grep bios\.forceSetupOnce '/vmfs/volumes/$datastore/$relpath' || echo \"$biosonce_config\" >> '/vmfs/volumes/$datastore/$relpath' && vim-cmd vmsvc/reload $1" > /dev/null
fi
output=$($ssh root@$esx_server "nohup vim-cmd vmsvc/power.on $1 2>&1 < /dev/null &")
if [ $? -eq 0 ] ; then
echo "VM powered on"
else
echo "$output" | sed -n 's/msg = "\(.*\)".*/\1/p'; return 1
fi
sleep 1
message=$($ssh root@$esx_server "vim-cmd vmsvc/message $1| head -1 | sed 's/Virtual machine message \(.*\):/\1/g'" )
if [[ $message != "No message." ]];then
$ssh root@$esx_server "vim-cmd vmsvc/message $1 $message 2"
fi
if [ -n "$autoyast" ];then
test -f ./vnc.rb || echo "Can't find vnc.rb, sorry: no autoyast string will be passed"
vmid2datastore $1
vmid2relpath $1
get_vnc_port
./vnc.rb "$esx_server" "$vnc_conn_port" test "netsetup=dhcp autoyast=$autoyast"
fi
}
power_off() {
output=$(ssh root@$esx_server "vim-cmd vmsvc/power.off $1 2>&1")
if [ $? -eq 0 ] ; then
echo "VM powered off"; return 0
else
echo "$output" | sed -n 's/msg = "\(.*\)".*/\1/p' ; return 1
fi
}
reset() {
output=$(ssh root@$esx_server "vim-cmd vmsvc/power.reset $1 2>&1")
if [ $? -eq 0 ] ; then
echo "VM resetted"; return 0
else
echo "$output" | sed -n 's/msg = "\(.*\)".*/\1/p' ; return 1
fi
}
snapshotcheck(){
output=$($ssh root@$esx_server "vim-cmd vmsvc/snapshot.get $1")
echo $output | grep -q "|-ROOT"
if [ $? -eq 1 ];then
return 2
fi
if [ -n "$2" ];then
echo $output | grep -q "$2"
if [ $? -eq 0 ];then
return 0
else
return 1
fi
fi
}
snapshot() {
charnumber=$(echo "$2" | wc -c)
if [ $charnumber -gt 81 ];then
snapname=$( echo "$2" | cut -c1-80)
echo "Snapshot name is too long, it was truncated to \"$snapname\""
fi
uniq=`$ssh root@$esx_server "vim-cmd vmsvc/snapshot.get $1|grep 'Snapshot Name'"`
echo $uniq |grep -o ": $snapname" > /dev/null
if [ $? -eq 1 ]
then
echo "Creating snapshot \"$snapname\"..."
$ssh root@$esx_server "vim-cmd vmsvc/snapshot.create $1 \"$snapname\" \" \" 1" > /dev/null
while true;do
snapshotcheck "$1" "$snapname" && break
sleep 10s
done
echo "Snapshot \"$snapname\" created";
else
echo "Snapshotname \"$snapname\" already exists"
fi
}
snapid2snapname(){
snaplist=$(snapshotlist $1)
echo "$snaplist"|grep -E -A1 "\-*$2\)"| sed -n 's/ <== You are here//;s/-*Snapshot Name\s*: \(.*\)/\1/p'
}
revert(){
snapname="$2"
if [ -n "$snapid" ];then
snapname=$(snapid2snapname $1 $snapid)
fi
if [ -z "$snapname" ];then
echo "There is no snapshot with ID: $snapid"
cleanup
fi
snaplevel=`$ssh root@$esx_server "vim-cmd vmsvc/snapshot.get $1 | grep '$snapname' | egrep -o '\-*'| wc -c"`
if [ ! $snaplevel -eq 0 ]
then
snaplevel=$(( $snaplevel/2-1))
$ssh root@$esx_server "vim-cmd vmsvc/snapshot.revert $1 suppressPowerOff $snaplevel" > /dev/null
echo "Reverted to snapshot: $snapname"
else
echo "No snapshot with specified name: $snapname"
fi
}
snapshotremove(){
if [ ! -z $3 ]
then
$ssh root@$esx_server "vim-cmd vmsvc/snapshot.removeall $1" > /dev/null
echo "Removing all snapshots..."
while true;do
snapshotcheck "$1"
if [ $? -eq 2 ];then
echo "All snapshots removed"; break
fi
sleep 10s
done
else
snapname="$2"
if [ -n "$snapid" ];then
snapname=$(snapid2snapname $1 $snapid)
fi
if [ -z "$snapname" ];then
echo "There is no snapshot with ID: $snapid"
cleanup
fi
snaplevel=$($ssh root@$esx_server "vim-cmd vmsvc/snapshot.get $1 | grep '$snapname' | egrep -o '\-*'| wc -c")
if [ ! $snaplevel -eq 0 ]
then
snaplevel=$(( $snaplevel/2-1))
$ssh root@$esx_server "vim-cmd vmsvc/snapshot.remove $1 1 $snaplevel" > /dev/null
while true;do
snapshotcheck "$1" "$snapname"
if [[ $? -eq 1 || $? -eq 2 ]];then
echo "Snapshot \"$snapname\" removed"; break
fi
sleep 10s
done
else
echo "No snapshot with specified name: $2"
fi
fi
}
get_current_snapshot(){
vmid2name $1
vmid2datastore $1
vmid2relpath $1
vmsdpath=$(echo $relpath | sed 's/\.vmx/\.vmsd/')
current_snapshot_uid=$($ssh root@$esx_server "cat '/vmfs/volumes/$datastore/$vmsdpath'| sed -n 's/snapshot.current = \"\(.*\)\"/\1/p'")
current_snapshot_name=$($ssh root@$esx_server "cat '/vmfs/volumes/$datastore/$vmsdpath'| grep -A3 -E 'snapshot.+\.uid = \"$current_snapshot_uid\"' |sed -n 's/snapshot.*\.displayName = \"\(.*\)\"/\1/p'")
echo $current_snapshot_name
}
snapshotlist(){
output=$($ssh root@$esx_server "vim-cmd vmsvc/snapshot.get $1")
echo "$output" | grep -q "|-ROOT"
if [ $? -eq 1 ];then
echo "No snaphots created for this VM"
else
get_current_snapshot $1
tempfile=/tmp/snapshotlist-`date +%s`-$RANDOM
echo "$output" > $tempfile
snapcounter=1
while read line
do
echo $line | grep -q '|-'
if [ $? -eq 0 ];then
line=$(echo $line | sed "s/|-/$snapcounter)/")
((snapcounter++))
fi
listed_snapshot_name=$(echo "$line" | sed -n 's/-*Snapshot Name\s*: \(.*\)/\1/p')
if [ "$listed_snapshot_name" = "$current_snapshot_name" ];then
line=$line" <== You are here"
fi
echo $line
done < $tempfile
rm -f $tempfile
fi
}
clone(){
powerstate $1
if [[ "$pwstate" = "Powered on" ]]; then
echo "You should switch the VM off before cloning. Please make a correct shutdown of the running OS or try '--poweroff $1'"
cleanup
fi
#yesno "This operation will remove all snapshots from the source Virtual Machine! Are you sure to proceed?"
#echo "Removing all snapshots..."
#$ssh root@$esx_server "vim-cmd vmsvc/snapshot.removeall $1" > /dev/null
#while true;do
# snapshotcheck $1
# if [ $? -eq 2 ];then
# break
# fi
# sleep 5s
#done
target_datastore="$datastore"
vmid2datastore $1
vmid2relpath $1
oldname=$(vmid2name $1; echo $name)
if [ -z "$name" ];then
name="Clone of $oldname "$(date +"%d-%m-%Y %T")
fi
relpath2vmdkpath
$ssh root@$esx_server "mkdir '/vmfs/volumes/$target_datastore/$name' && vmkfstools -d thin -i '/vmfs/volumes/$datastore/$vmdkpath' '/vmfs/volumes/$target_datastore/$name/$name.vmdk' && cp '/vmfs/volumes/$datastore/$relpath' '/vmfs/volumes/$target_datastore/$name/$name.vmx'"
clone_failed="0"
if [ -n "$to_server" ]; then
ssh="$ssh -t" # we need a terminal allocation for scp
$ssh root@$esx_server "scp -r '/vmfs/volumes/$target_datastore/$name' 'root@$to_server:/vmfs/volumes/$target_datastore/'"
if [ $? -eq 0 ] ; then
echo "$name virtual machine transferred to $to_server"
else
echo "Secure copy(scp) of VM to $to_server failed"; clone_failed="1"
fi
$ssh root@$esx_server "cd '/vmfs/volumes/$target_datastore/$name' && rm ./* && cd .. && rmdir './$name'" # yes, i'm afraid of scripting rm -rf in any forms
#here we are switching the server for the first time, no ssh master yet
ssh='ssh'
esx_server="$to_server"
fi
if [ "$clone_failed" != "1" ]; then
vnc_port
$ssh root@$esx_server "sed -i 's/displayname = \".*\"/displayname = \"$name\"/gI;s/\".*\.vmdk\"/\"$name.vmdk\"/g;s/RemoteDisplay.vnc.port = .*/RemoteDisplay.vnc.port = \"$vnc_port\"/gI' '/vmfs/volumes/$target_datastore/$name/$name.vmx'"
$ssh root@$esx_server "vim-cmd solo/registervm '/vmfs/volumes/$target_datastore/$name/$name.vmx' && echo '\"$oldname\" was successfuly cloned to \"$name\"'"
fi
}
remove() {
powerstate $1
vmid2name $1 || exit
if [[ "$pwstate" = "Powered on" ]]; then
echo "You should switch the VM off before removal: try '--poweroff $1' first"
return 1
fi
if yesno "Do you really want to delete $name ?" ; then
output=$($ssh root@$esx_server "vim-cmd vmsvc/destroy $1 2>&1")
if [ $? -eq 0 ] ; then
echo "$name virtual machine removed"; return 0
else
echo "$output" | sed -n 's/msg = "\(.*\)".*/\1/p'; return 1
fi
fi
}
powerstate(){
pwstate=$($ssh root@$esx_server "vim-cmd vmsvc/power.getstate $1 2>&1")
if [ $? -eq 0 ] ; then
pwstate=$(echo "$pwstate"|tail -1)
else
echo "$pwstate" | sed -n 's/msg = "\(.*\)".*/\1/p'; cleanup
fi
}
vnc_conf(){
if [ -n "$vnc_password" ]
then
vnc_config="
RemoteDisplay.vnc.enabled = \"True\"
RemoteDisplay.vnc.port = \"$vnc_port\"
RemoteDisplay.vnc.password = \"$vnc_password\""
else
vnc_config="
RemoteDisplay.vnc.enabled = \"True\"
RemoteDisplay.vnc.port = \"$vnc_port\""
fi
}
addvnc() {
vmid2name $1
vmid2datastore $1
vmid2relpath $1
vnc_check=`$ssh root@$esx_server "egrep 'RemoteDisplay.vnc.enabled = \"?True\"?' '/vmfs/volumes/$datastore/$relpath'"`
if [ ! -z "$vnc_check" ]
then echo "VNC is already enabled on this machine"
else
powerstate $1
if [ "$pwstate" = "Powered on" ]
then
echo "Please power off this VM before adding VNC support"; cleanup;
fi
vnc_port
vnc_pass
vnc_conf
$ssh root@$esx_server "echo -e \"$vnc_config\" >> 'vmfs/volumes/$datastore/$relpath' && vim-cmd vmsvc/reload $1"
fi
}
dslist() {
if [ -n "$vmfsonly" ]; then
$ssh root@$esx_server "vim-cmd hostsvc/datastore/listsummary" | grep VMFS -B7 | grep name | sed -n 's/name = "\(.*\)",/\1/gp' |sed 's/^[ \t]*//;s/[ \t]*$//'|sort
else
$ssh root@$esx_server "vim-cmd hostsvc/datastore/listsummary" | grep name | awk {'print $3'} | sed 's/",*//g' | sort
fi
}
dsbrowse() {
$ssh root@$esx_server "ls -1 /vmfs/volumes/$1/"
}
export2desktop(){
vmid2name $1 || cleanup
vmid2datastore $1
vmid2relpath $1
relpath2vmdkpath
export_dir=$name"_export"
local_export_dir=${local_export_dir:-"./"}
$ssh root@$esx_server "cd '/vmfs/volumes/$datastore/$(dirname "$relpath")' && mkdir './$export_dir' && vmkfstools -i '/vmfs/volumes/$datastore/$vmdkpath' -d 2gbsparse './$export_dir/$name.vmdk' && cp '/vmfs/volumes/$datastore/$relpath' './$export_dir' && sed -i 's/\".*\.vmdk\"/\"$name.vmdk\"/g' './$export_dir/$(basename "$relpath")'"
$scp -r "root@$esx_server:'/vmfs/volumes/$datastore/$(dirname "$relpath")/$export_dir'" "$local_export_dir"
$ssh root@$esx_server "rm -rf '/vmfs/volumes/$datastore/$(dirname "$relpath")/$export_dir'"
}
#virtual switch management
vswitcheslist()
{
$ssh root@$esx_server "esxcfg-vswitch -l"
}
niclist()
{
$ssh root@$esx_server "esxcfg-nics -l"
}
networks()
{
nets=$($ssh root@$esx_server "vim-cmd vmsvc/get.networks $1 | sed -n 's/name = \"\(.*\)\",/\1/gp' | sed 's/^[ \t]*//;s/[ \t]*$//'")
echo "$nets"| while read line
do
counter=${counter:-1}
echo "$counter) \"$line\""
counter=$(($counter+1))