An effective approach for gaining persistence is to use the Meterpreter prompt's persistence script. Note that this module in Meterpreter has been replaced with post-exploit modules; however, the following example still works in the latest version of Metasploit as of January 2019.
After a system has been exploited and the migrate command has moved the initial shell to a more secure service, an attacker can invoke the persistence script from the Meterpreter prompt.
Using -h in the command will identify the available options for creating a persistent backdoor, as shown in the following screenshot:
In the example shown in the following screenshot, we have configured persistence to run automatically when the system boots, and to attempt to connect to our listener every 5 seconds. The listener is identified as the remote system (-r), with a specific IP address and port.
Additionally, we could elect to use the -U option, which will start persistence when a user logs in to the system:
The persistence script places a VBS file in a temporary directory; however, you can use the -L option to specify a different location. The script also adds that file to the local autorun sections of the registry.
Because the persistence script is not authenticated and anyone can use it to access the compromised system, it should be removed from the system as soon as possible after the discovery or completion of penetration testing. To remove the script, confirm the location of the resource file for cleanup, and then execute the following resource command:
meterpreter>run multi_console_command -rc /root/.msf4/logs/persistence/VICTIM_20170610.4514/VICTIM_20170610.4514.rc