Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Bash shell script that reads RDP files - updated

The story

last updated 2017-01-18 In my migration to linux, I wanted a shell script that can read the Microsoft rdp file format. I still need to connect to my Windows systems. There are multiple packages that can do the task of connecting (I went with xfreerdp), but none that can intrinsically read the rdp files that the mstsc tool can save. So, I wrote one. I'm sure someday I will have a github or gitlab account for hosting my stuff. But for now, here's some Wordpress

 code for you.
You can find this rdp.sh script in my bgscripts package on github. Go check it out!

The RDP.sh script

  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
#!/bin/sh
# Filename: RDP.sh
# Location:
# Author: bgstack15@gmail.com
# Startdate: 2016-02-08 11:55:31
# Title: Script that Opens RDP Connections Based on RDP Files
# Purpose:
# Package:
# History:
# Usage:
# Reference: ftemplate.sh 2016-02-02a; framework.sh 2016-02-02a
#   https://github.com/FreeRDP/FreeRDP/wiki/CommandLineInterface
# Improve:
#    Warning: Some systems don't like the clipboard sharing, including Hulk.
fiversion="2016-02-02a"
RDPversion="2016-02-08a"

usage() {
   less -F >&2 <<ENDUSAGE
usage: RDP.sh [-duV] [-i infile1]
version ${RDPversion}
 -d debug   Show debugging info, including parsed variables.
 -u usage   Show this usage block.
 -V version Show script version number.
 -i infile  Overrides default infile value. Default is none.
Return values:
0 Normal
1 Help or version info displayed
2 Count or type of flaglessvals is incorrect
3 Incorrect OS type
4 Unable to find dependency
5 Not run as root or sudo
ENDUSAGE
}

# DEFINE FUNCTIONS
function getscreensize {
   # call: getscreensize thisheight thiswidth
   # assigns W and H to the 2 variables sent to the function
   calledvar1=${1-thiswidth}
   calledvar2=${2-thisheight}
   thisfile=$(mktemp -u)
  
   # exact methods will differ depending on available packages and distros
   # Korora 22
   grep -qiE "(Fedora|Korora).*(22|23)" /etc/redhat-release 2>/dev/null && \
      xdpyinfo | grep -oiE "dimensions.*[0-9]{3,4}x[0-9]{3,4} pi" | tr -d '[A-Za-wyz ():]' | tr 'x' ' ' > ${thisfile}
   read myx myy < ${thisfile}
   eval "${calledvar1}=\${myx}"
   eval "${calledvar2}=\${myy}"
   rm -rf ${thisfile}
}

function getuser {
   # call: getuser "${userfile}" thisuser thispassword
   # read fstab credentials file "userfile" and place in strings thisuser and thispassword
   # Note: This gets user in domain\username format.

   calledvar1=${2-thisuser}
   calledvar2=${3-thispassword}

   [[ -n "$1" ]] && thisinfile="$1"
   if [[ -f "${thisinfile}" ]];
   then
      for word in $( fsudo grep -viE "^$|^#" "${thisinfile}" );
      do
         item="${word%%=*}"
         value="${word##*=}"
         case "${item}" in
            domain) usertemp="${value}\\${usertemp}";;
            username|user) usertemp="${usertemp}${value}";;
            password) passtemp="${value}";;
            *) [ ];; #other item is useless
         esac
      done
   else
      # not a valid file, so get username from environment
      domain=$( hostname -d )
      usertemp="${domain}\\$USER"
   fi

   eval "$calledvar1=\$usertemp"
   eval "$calledvar2=\$passtemp"

}

# DEFINE TRAPS

function clean_RDP {
   #rm -f $logfile >/dev/null 2>&1
   [ ] #use at end of entire script if you need to clean up tmpfiles
}

function CTRLC {
   #trap "CTRLC" 2
   [ ] #useful for controlling the ctrl+c keystroke
}

function CTRLZ {
   #trap "CTRLZ" 18
   [ ] #useful for controlling the ctrl+z keystroke
}

function parseFlag {
   flag=$1
   hasval=0
   case $flag in
      # INSERT FLAGS HERE
      "d" | "debug" | "DEBUG" | "dd" ) setdebug; ferror "debug level ${debug}";;
      "u" | "usage" | "help") usage; exit 1;;
      "V" | "fcheck" | "version") ferror "${scriptfile} version ${RDPversion}"; exit 1;;
      #"i" | "infile" | "inputfile") getval;infile1=$tempval;;
   esac
  
   debuglev 10 && { [[ hasval -eq 1 ]] && ferror "flag: $flag = $tempval" || ferror "flag: $flag"; }
}

# DETERMINE LOCATION OF FRAMEWORK
while read flocation; do if [[ -x $flocation ]] && [[ $( $flocation --fcheck ) -ge 20151123 ]]; then frameworkscript=$flocation; break; fi; done <<EOFLOCATIONS
./framework.sh
${scriptdir}/framework.sh
~/bin/bgscripts/framework.sh
~/bin/framework.sh
~/bgscripts/framework.sh
~/framework.sh
/usr/local/bin/bgscripts/framework.sh
/usr/local/bin/framework.sh
/usr/bin/bgscripts/framework.sh
/usr/bin/framework.sh
/usr/bgscripts/framework.sh
/usr/framework.sh
/bin/bgscripts/framework.sh
/bin/framework.sh
/mnt/scripts/bgscripts/framework.sh
/usr/libexec/bgscripts/framework.sh
EOFLOCATIONS
[[ -z "$frameworkscript" ]] && echo "$0: framework not found. Aborted." 1>&2 && exit 4

# REACT TO OPERATING SYSTEM TYPE
case $( uname -s ) in
   AIX) [ ];;
   Linux) [ ];;
   *) echo "$scriptfile: 3. Indeterminate OS: $( uname -s )" 1>&2 && exit 3;;
esac

# INITIALIZE VARIABLES
# variables set in framework:
# today server thistty scriptdir scriptfile scripttrim
# is_cronjob stdin_piped stdout_piped stderr_piped sendsh sendopts
. ${frameworkscript} || echo "$0: framework did not run properly. Continuing..." 1>&2
infile1=
outfile1=
logfile=${scriptdir}/${scripttrim}.${today}.out
interestedparties="bgstack15@example.com"
rdpcommand=/usr/bin/xfreerdp
alloptions="/sec-rdp"; #where defaults go. Will be added to by infile1 options
userfile=~/.bgstack15.example.com
fullscreenborder=80px;

## REACT TO ROOT STATUS
#case $is_root in
#   1) # proper root
#      [ ] ;;
#   sudo) # sudo to root
#      [ ] ;;
#   "") # not root at all
#      #ferror "${scriptfile}: 5. Please run as root or sudo. Aborted."
#      #exit 5
#      [ ]
#      ;;
#esac

# SET CUSTOM SCRIPT AND VALUES
#setval 1 sendsh sendopts<<EOFSENDSH      # if $1="1" then setvalout="critical-fail" on failure
#/usr/local/bin/bgscripts/send.sh -hs     #                setvalout maybe be "fail" otherwise
#/usr/local/bin/send.sh -hs               # on success, setvalout="valid-sendsh"
#/usr/bin/mail -s
#EOFSENDSH
#[[ "$setvalout" = "critical-fail" ]] && ferror "${scriptfile}: 4. mailer not found. Aborted." && exit 4

# VALIDATE PARAMETERS
# objects before the dash are options, which get filled with the optvals
# to debug flags, use option DEBUG. Variables set in framework: fallopts
validateparams infile1 - "$@"

# CONFIRM TOTAL NUMBER OF FLAGLESSVALS IS CORRECT
if [[ $thiscount -lt 1 ]];
then
   ferror "${scriptfile}: 2. Fewer than 1 flaglessvals. Aborted."
   exit 2
fi

# CONFIGURE VARIABLES AFTER PARAMETERS

# READ CONFIG FILE
remember_IFS="${IFS}"; IFS=$'\n'
the_raw_data=($(cat "${infile1}"))
IFS="${remember_IFS}"

unhandled="unhandled:";
sizes=0;
#grep -viE "^$|^#" "${infile1}" | sed "s/[^\]#.*$//;' | while read line
#BASH BELOW
#while read -r line
for line in "${the_raw_data[@]}"
do
   debuglev 5 && ferror "$line"
   value=$( echo "${line##*:}" | tr -d '\r' )
   #read -p "Please type something here:" response < $thistty
   #echo "$response"
   case "${line}" in
      *screen\ mode\ id*)    screenmode="${value}";;
      use\ multimon*)        multimon="${value}";;
      desktopwidth*)        desktopwidth="${value}";((sizes+=10));;
      desktopheight*)        desktopheight="${value}";((sizes+=1));;
      session\ bpp*)        sessionbpp="${value}";;
      full\ address*)        fulladdress="${value}";; #should include port if necessary
      compression*)        compression="${value}";;
      displayconnectionbar*)    displayconnectionbar="${value}";; # guessing that this is /disp
      audiomode*)        audiomode="${value}";;
      audiocapturemode*)    audiocapturemode="${value}";;
      keyboardhook*)        unhandled="${unhandled}\n${line}";; #cannot find implementation in freerdp
      redirectclipboard*)    clipboard="${value}";;
      disable\ wallpaper*)    wallpaper="${value}";;
      allow\ font\ smoothing*)    fontsmoothing="${value}";;
      allow\ desktop\ composition*)    unhandled="${unhandled}\n${line}";; # provides aero but I never ever use aero
      disable\ full\ window\ drag*)    windowdrag="${value}";;
      disable\ menu\ anims*)    menuanims="${value}";;
      disable\ themes*)        themes="${value}";;
      *) debuglev 4 && ferror "Unknown option: ${line}";;
   esac
done
#BASH BELOW
#done < <( grep -viE "^$|^#" "${infile1}" | sed 's/[^\]#.*$//g;' )

#GET USER
getuser "${userfile}" thisuser thispassword

#FINISH PARSING DIRECTIVES FOR freerdp
[[ "${multimon}" = "1" ]] && alloptions="${alloptions} /multimon"
echo "screenmode=${screenmode}"
if [[ "${screenmode}" = "1" ]];
then
   # screenmode 1 windowed
   case sizes in
      0) screenmode=2;; #abort and just do fullscreen
      1) alloptions="${alloptions} /h:${desktopheight}";;
      10) alloptions="${alloptions} /w:${desktopwidth}";;
      11) alloptions="${alloptions} /size:${desktopwidth}x${desktopheight}";;
      *) ferror "Did not understand sizing. Emulating fullscreen." && screenmode=2;;
   esac
fi
if [[ "${screenmode}" = "2" ]];
then
   # screenmode 2 fullscreen

   # on linux make that windowed but 20px border around window
   # xfreerdp has the "/f" flag though if I want to change it in the future
   getscreensize thiswidth thisheight
   fullscreenborder=${fullscreenborder%%px}
   ((thiswidth-=fullscreenborder)) && ((thisheight -=fullscreenborder))

   alloptions="${alloptions} /size:${thiswidth}x${thisheight}"
fi
[[ -n "${sessionbpp}" ]] && alloptions="${alloptions} /bpp:${sessionbpp}"
[[ -n "${fulladdress}" ]] && alloptions="${alloptions} /v:${fulladdress}"
[[ -n "${compression}" ]] && alloptions="${alloptions} -z"
[[ "${displayconnectionbar}" = "1" ]] && alloptions="${alloptions} /disp"
[[ -n "${audiomode}" ]] && alloptions="${alloptions} /audio-mode:${audiomode}"
[[ -n "${audiocapturemode}" ]] && alloptions="${alloptions} /mic"
[[ "${clipboard}" = "1" ]] && alloptions="${alloptions} +clipboard"
[[ "${wallpaper}" = "0" ]] && alloptions="${alloptions} /wallpaper" #because it is actually a disable-wallpaper flag
[[ "${fontsmoothing}" = "1" ]] && alloptions="${alloptions} /fonts"
[[ "${windowdrag}" = "0" ]] && alloptions="${alloptions} /window-drag"
[[ "${menuanims}" = "0" ]] && alloptions="${alloptions} /menu-anims"
[[ "${themes}" = "0" ]] && alloptions="${alloptions} /themes"
alloptions="${alloptions} /u:${thisuser} /p:${thispassword}"

alloptions="${alloptions# }" # to trim leading space just to look nicer

## REACT TO BEING A CRONJOB
#if [[ $is_cronjob -eq 1 ]];
#then
#   [ ]
#else
#   [ ]
#fi

# SET TRAPS
#trap "CTRLC" 2
#trap "CTRLZ" 18
#trap "clean_RDP" 0

# MAIN LOOP
#{
   debuglev 1 && echo ${rdpcommand} ${alloptions} || \
      ${rdpcommand} ${alloptions}
   [ ]
#} | tee -a $logfile

# EMAIL LOGFILE
#$sendsh $sendopts "$server $scriptfile out" $logfile $interestedparties

Comments