sudo supports the -c option, which passes the command to the sub-shell. Here are some of the sudo flags you might find useful:
-c, --command=COMMAND pass a single COMMAND to the shell with -c --session-command=COMMAND pass a single COMMAND to the shell with -c and do not create a new session -m, --preserve-environment do not reset environment variables -s, --shell=SHELL run SHELL if /etc/shells allows it
So, using something like sudo su someuser -c 'ls;date' , you will run the ls and date someuser as someuser . Try a command line on this host to understand what you can do, and then apply it to an SSH session.
See man sudo more details.
As well as a hint for coding, you can reduce:
if data =~ /\[sudo\]/ || data =~ /Password/i
in
if (data[/\[sudo\]|Password/i])
source share